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
|
|---|---|---|---|---|---|---|---|
juspay/hyperswitch
|
juspay__hyperswitch-4103
|
Bug: fix: populate merchant connector id and profile id in payments list
Currently in payments list response, merchant connector id and profile id is not getting populated for payments list response, though the value is present in db.
|
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index 315ddd3b39b..313d520fdac 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -952,6 +952,8 @@ impl ForeignFrom<(storage::PaymentIntent, storage::PaymentAttempt)> for api::Pay
authentication_type: pa.authentication_type,
connector_transaction_id: pa.connector_transaction_id,
attempt_count: pi.attempt_count,
+ profile_id: pi.profile_id,
+ merchant_connector_id: pa.merchant_connector_id,
..Default::default()
}
}
|
2024-03-15T09:14:10Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
`Profile_id` and `merchant_connector_id` is to be populated for payments 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
closes #4103
## How did you test it?
Use the curl to get payments list:
```
curl --location 'http://localhost:8080/payments/list' \
--header 'Content-Type: application/json' \
--header 'Cookie: token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMWZjNzgyOTUtM2JiMy00OGJjLThlZDgtNzFjMzVjMzMxYWU2IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNjk3NzE2ODcwIiwicm9sZV9pZCI6Im1lcmNoYW50X2FkbWluIiwiZXhwIjoxNjk3ODg5NjcxLCJvcmdfaWQiOiJvcmdfejQ5ZExMeTdmbllUODN5TDY3clEifQ.CJzEQ2qbhn-qUiiVBSdvCJiLvWp-5wCF9R54gth6QbQ' \
--header 'Authorization: Bearer JWT' \
--data '{
}'
```
In Response fields `profile_id` and `merchant_connector_id` fields properly populated.
```
{
"count": 5,
"total_count": 100,
"data": [
{
"payment_id": "test_fhYXl6ExKokyMqAlnDiz",
"merchant_id": "merchant_1710153863",
"status": "succeeded",
"amount": 16700,
"net_amount": 0,
"amount_capturable": 16700,
"amount_received": null,
"connector": "stripe_test",
"client_secret": "test_fhYXl6ExKokyMqAlnDiz_secret_0Lfp0rpudua13MFoT8NU",
"created": "2024-03-14T08:10:15.000Z",
"currency": "USD",
"customer_id": "hs-dashboard-user",
"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": null,
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": null,
"authentication_type": "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_fhYXl6ExKokyMqAlnDiz_1",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_4TBk8LY9HGp5dGXqxFTF",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "test",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": null,
"expires_on": null,
"fingerprint": null,
"payment_method_id": null,
"payment_method_status": null
},
{
"payment_id": "test_ejaOwTOxyNQu5WrDeZnk",
"merchant_id": "merchant_1710153863",
"status": "succeeded",
"amount": 14600,
"net_amount": 0,
"amount_capturable": 14600,
"amount_received": null,
"connector": "paypal_test",
"client_secret": "test_ejaOwTOxyNQu5WrDeZnk_secret_l6jUZkSzjkNpa8xnzwwj",
"created": "2024-03-14T05:25:35.000Z",
"currency": "USD",
"customer_id": "hs-dashboard-user",
"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": 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_ejaOwTOxyNQu5WrDeZnk_1",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_4TBk8LY9HGp5dGXqxFTF",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "test",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": null,
"expires_on": null,
"fingerprint": null,
"payment_method_id": null,
"payment_method_status": null
},
{
"payment_id": "test_MB9kqEtqMONlQEPHb1dT",
"merchant_id": "merchant_1710153863",
"status": "succeeded",
"amount": 12900,
"net_amount": 0,
"amount_capturable": 12900,
"amount_received": null,
"connector": "stripe_test",
"client_secret": "test_MB9kqEtqMONlQEPHb1dT_secret_kSeuhHJkrZcBndgMWRP2",
"created": "2024-03-14T05:02:09.000Z",
"currency": "USD",
"customer_id": "hs-dashboard-user",
"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": null,
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": null,
"authentication_type": "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": "debit",
"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_MB9kqEtqMONlQEPHb1dT_1",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_4TBk8LY9HGp5dGXqxFTF",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "test",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": null,
"expires_on": null,
"fingerprint": null,
"payment_method_id": null,
"payment_method_status": null
},
{
"payment_id": "test_kWl22oD2BdhPq3LM260p",
"merchant_id": "merchant_1710153863",
"status": "succeeded",
"amount": 11100,
"net_amount": 0,
"amount_capturable": 11100,
"amount_received": null,
"connector": "paypal_test",
"client_secret": "test_kWl22oD2BdhPq3LM260p_secret_1KRPGPVx25PyjGcowDti",
"created": "2024-03-14T04:27:59.000Z",
"currency": "USD",
"customer_id": "hs-dashboard-user",
"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": 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": "debit",
"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_kWl22oD2BdhPq3LM260p_1",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_4TBk8LY9HGp5dGXqxFTF",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "test",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": null,
"expires_on": null,
"fingerprint": null,
"payment_method_id": null,
"payment_method_status": null
},
{
"payment_id": "test_uNRkJ3WbgCmZr7CF58Ev",
"merchant_id": "merchant_1710153863",
"status": "succeeded",
"amount": 12900,
"net_amount": 0,
"amount_capturable": 12900,
"amount_received": null,
"connector": "stripe_test",
"client_secret": "test_uNRkJ3WbgCmZr7CF58Ev_secret_yzc8nAG4qTdQVpSjmnwP",
"created": "2024-03-14T03:43:12.000Z",
"currency": "USD",
"customer_id": "hs-dashboard-user",
"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": null,
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": null,
"name": null,
"phone": null,
"return_url": null,
"authentication_type": "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": "debit",
"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_uNRkJ3WbgCmZr7CF58Ev_1",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_4TBk8LY9HGp5dGXqxFTF",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "test",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": null,
"expires_on": null,
"fingerprint": null,
"payment_method_id": null,
"payment_method_status": 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
f9db641058179b846d4bf3ce69a7679b4e9541fc
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4117
|
Bug: Add span metadata to `tokio` spawned futures
Add span metadata to `tokio` spawned futures, as logs do not have parent span context.
|
diff --git a/crates/common_utils/src/macros.rs b/crates/common_utils/src/macros.rs
index c07b2112db2..b8d5743d8fe 100644
--- a/crates/common_utils/src/macros.rs
+++ b/crates/common_utils/src/macros.rs
@@ -47,13 +47,6 @@ macro_rules! newtype {
};
}
-#[macro_export]
-macro_rules! async_spawn {
- ($t:block) => {
- tokio::spawn(async move { $t });
- };
-}
-
/// Use this to ensure that the corresponding
/// openapi route has been implemented in the openapi crate
#[macro_export]
diff --git a/crates/diesel_models/src/lib.rs b/crates/diesel_models/src/lib.rs
index 44e4d174537..27bf11a7e6f 100644
--- a/crates/diesel_models/src/lib.rs
+++ b/crates/diesel_models/src/lib.rs
@@ -24,7 +24,6 @@ pub mod gsm;
#[cfg(feature = "kv_store")]
pub mod kv;
pub mod locker_mock_up;
-pub mod macros;
pub mod mandate;
pub mod merchant_account;
pub mod merchant_connector_account;
diff --git a/crates/diesel_models/src/macros.rs b/crates/diesel_models/src/macros.rs
deleted file mode 100644
index de3596ecc10..00000000000
--- a/crates/diesel_models/src/macros.rs
+++ /dev/null
@@ -1,6 +0,0 @@
-#[macro_export]
-macro_rules! async_spawn {
- ($t:block) => {
- tokio::spawn(async move { $t });
- };
-}
diff --git a/crates/drainer/src/handler.rs b/crates/drainer/src/handler.rs
index 5aa902d84c5..47b60db80d5 100644
--- a/crates/drainer/src/handler.rs
+++ b/crates/drainer/src/handler.rs
@@ -1,5 +1,6 @@
use std::sync::{atomic, Arc};
+use router_env::tracing::Instrument;
use tokio::{
sync::{mpsc, oneshot},
time::{self, Duration},
@@ -68,13 +69,16 @@ impl Handler {
while self.running.load(atomic::Ordering::SeqCst) {
metrics::DRAINER_HEALTH.add(&metrics::CONTEXT, 1, &[]);
if self.store.is_stream_available(stream_index).await {
- tokio::spawn(drainer_handler(
- self.store.clone(),
- stream_index,
- self.conf.max_read_count,
- self.active_tasks.clone(),
- jobs_picked.clone(),
- ));
+ let _task_handle = tokio::spawn(
+ drainer_handler(
+ self.store.clone(),
+ stream_index,
+ self.conf.max_read_count,
+ self.active_tasks.clone(),
+ jobs_picked.clone(),
+ )
+ .in_current_span(),
+ );
}
stream_index = utils::increment_stream_index(
(stream_index, jobs_picked.clone()),
@@ -116,10 +120,12 @@ impl Handler {
let redis_conn_clone = self.store.redis_conn.clone();
// Spawn a task to monitor if redis is down or not
- tokio::spawn(async move { redis_conn_clone.on_error(redis_error_tx).await });
+ let _task_handle = tokio::spawn(
+ async move { redis_conn_clone.on_error(redis_error_tx).await }.in_current_span(),
+ );
//Spawns a task to send shutdown signal if redis goes down
- tokio::spawn(redis_error_receiver(redis_error_rx, tx));
+ let _task_handle = tokio::spawn(redis_error_receiver(redis_error_rx, tx).in_current_span());
Ok(())
}
diff --git a/crates/drainer/src/lib.rs b/crates/drainer/src/lib.rs
index 0ed6183faef..e7ae7621365 100644
--- a/crates/drainer/src/lib.rs
+++ b/crates/drainer/src/lib.rs
@@ -18,7 +18,10 @@ use common_utils::signals::get_allowed_signals;
use diesel_models::kv;
use error_stack::{IntoReport, ResultExt};
use hyperswitch_interfaces::secrets_interface::secret_state::RawSecret;
-use router_env::{instrument, tracing};
+use router_env::{
+ instrument,
+ tracing::{self, Instrument},
+};
use tokio::sync::mpsc;
pub(crate) type Settings = crate::settings::Settings<RawSecret>;
@@ -39,7 +42,8 @@ pub async fn start_drainer(store: Arc<Store>, conf: DrainerSettings) -> errors::
"Failed while getting allowed signals".to_string(),
))?;
let handle = signal.handle();
- let task_handle = tokio::spawn(common_utils::signals::signal_handler(signal, tx.clone()));
+ let task_handle =
+ tokio::spawn(common_utils::signals::signal_handler(signal, tx.clone()).in_current_span());
let handler_clone = drainer_handler.clone();
diff --git a/crates/router/src/bin/scheduler.rs b/crates/router/src/bin/scheduler.rs
index c586bfecdb7..1df37e9f6d1 100644
--- a/crates/router/src/bin/scheduler.rs
+++ b/crates/router/src/bin/scheduler.rs
@@ -16,7 +16,10 @@ use router::{
services::{self, api},
workflows,
};
-use router_env::{instrument, tracing};
+use router_env::{
+ instrument,
+ tracing::{self, Instrument},
+};
use scheduler::{
consumer::workflows::ProcessTrackerWorkflow, errors::ProcessTrackerError,
workflows::ProcessTrackerWorkflows, SchedulerAppState,
@@ -49,10 +52,9 @@ async fn main() -> CustomResult<(), ProcessTrackerError> {
.await;
// channel to shutdown scheduler gracefully
let (tx, rx) = mpsc::channel(1);
- tokio::spawn(router::receiver_for_error(
- redis_shutdown_signal_rx,
- tx.clone(),
- ));
+ let _task_handle = tokio::spawn(
+ router::receiver_for_error(redis_shutdown_signal_rx, tx.clone()).in_current_span(),
+ );
#[allow(clippy::expect_used)]
let scheduler_flow_str =
@@ -81,10 +83,13 @@ async fn main() -> CustomResult<(), ProcessTrackerError> {
.await
.expect("Failed to create the server");
- tokio::spawn(async move {
- let _ = web_server.await;
- logger::error!("The health check probe stopped working!");
- });
+ let _task_handle = tokio::spawn(
+ async move {
+ let _ = web_server.await;
+ logger::error!("The health check probe stopped working!");
+ }
+ .in_current_span(),
+ );
logger::debug!(startup_config=?state.conf);
diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs
index efc0e8852da..7757313d867 100644
--- a/crates/router/src/core/payments/flows/authorize_flow.rs
+++ b/crates/router/src/core/payments/flows/authorize_flow.rs
@@ -1,5 +1,6 @@
use async_trait::async_trait;
use error_stack;
+use router_env::tracing::Instrument;
use super::{ConstructFlowSpecificData, Feature};
use crate::{
@@ -125,26 +126,32 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu
let state = state.clone();
logger::info!("Call to save_payment_method in locker");
- tokio::spawn(async move {
- logger::info!("Starting async call to save_payment_method in locker");
-
- let result = Box::pin(tokenization::save_payment_method(
- &state,
- &connector,
- response,
- &maybe_customer,
- &merchant_account,
- self.request.payment_method_type,
- &key_store,
- Some(resp.request.amount),
- Some(resp.request.currency),
- ))
- .await;
-
- if let Err(err) = result {
- logger::error!("Asynchronously saving card in locker failed : {:?}", err);
+ let _task_handle = tokio::spawn(
+ async move {
+ logger::info!("Starting async call to save_payment_method in locker");
+
+ let result = Box::pin(tokenization::save_payment_method(
+ &state,
+ &connector,
+ response,
+ &maybe_customer,
+ &merchant_account,
+ self.request.payment_method_type,
+ &key_store,
+ Some(resp.request.amount),
+ Some(resp.request.currency),
+ ))
+ .await;
+
+ if let Err(err) = result {
+ logger::error!(
+ "Asynchronously saving card in locker failed : {:?}",
+ err
+ );
+ }
}
- });
+ .in_current_span(),
+ );
Ok(resp)
}
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index 97b1d8e9817..b0bdc921107 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -160,18 +160,21 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
let store = state.store.clone();
- let business_profile_fut = tokio::spawn(async move {
- store
- .find_business_profile_by_profile_id(&profile_id)
- .map(|business_profile_result| {
- business_profile_result.to_not_found_response(
- errors::ApiErrorResponse::BusinessProfileNotFound {
- id: profile_id.to_string(),
- },
- )
- })
- .await
- });
+ let business_profile_fut = tokio::spawn(
+ async move {
+ store
+ .find_business_profile_by_profile_id(&profile_id)
+ .map(|business_profile_result| {
+ business_profile_result.to_not_found_response(
+ errors::ApiErrorResponse::BusinessProfileNotFound {
+ id: profile_id.to_string(),
+ },
+ )
+ })
+ .await
+ }
+ .in_current_span(),
+ );
let store = state.store.clone();
@@ -498,13 +501,17 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
let store = state.clone().store;
- let additional_pm_data_fut = tokio::spawn(async move {
- Ok(n_request_payment_method_data
- .async_map(|payment_method_data| async move {
- helpers::get_additional_payment_data(&payment_method_data, store.as_ref()).await
- })
- .await)
- });
+ let additional_pm_data_fut = tokio::spawn(
+ async move {
+ Ok(n_request_payment_method_data
+ .async_map(|payment_method_data| async move {
+ helpers::get_additional_payment_data(&payment_method_data, store.as_ref())
+ .await
+ })
+ .await)
+ }
+ .in_current_span(),
+ );
let store = state.clone().store;
diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs
index 97d981c68eb..efba097d92d 100644
--- a/crates/router/src/lib.rs
+++ b/crates/router/src/lib.rs
@@ -31,6 +31,7 @@ use actix_web::{
};
use http::StatusCode;
use hyperswitch_interfaces::secrets_interface::secret_state::SecuredSecret;
+use router_env::tracing::Instrument;
use routes::AppState;
use storage_impl::errors::ApplicationResult;
use tokio::sync::{mpsc, oneshot};
@@ -195,7 +196,7 @@ pub async fn start_server(conf: settings::Settings<SecuredSecret>) -> Applicatio
.workers(server.workers)
.shutdown_timeout(server.shutdown_timeout)
.run();
- tokio::spawn(receiver_for_error(rx, server.handle()));
+ let _task_handle = tokio::spawn(receiver_for_error(rx, server.handle()).in_current_span());
Ok(server)
}
diff --git a/crates/router/tests/utils.rs b/crates/router/tests/utils.rs
index e1ab3e80f32..5d48d6e8ad0 100644
--- a/crates/router/tests/utils.rs
+++ b/crates/router/tests/utils.rs
@@ -12,6 +12,7 @@ use actix_web::{
};
use derive_deref::Deref;
use router::{configs::settings::Settings, routes::AppState, services};
+use router_env::tracing::Instrument;
use serde::{de::DeserializeOwned, Deserialize};
use serde_json::{json, Value};
use tokio::sync::{oneshot, OnceCell};
@@ -24,7 +25,7 @@ async fn spawn_server() -> bool {
.await
.expect("failed to create server");
- let _server = tokio::spawn(server);
+ let _server = tokio::spawn(server.in_current_span());
true
}
diff --git a/crates/scheduler/src/consumer.rs b/crates/scheduler/src/consumer.rs
index e069db28da7..471f689ffc8 100644
--- a/crates/scheduler/src/consumer.rs
+++ b/crates/scheduler/src/consumer.rs
@@ -10,7 +10,10 @@ pub use diesel_models::{self, process_tracker as storage};
use error_stack::{IntoReport, ResultExt};
use futures::future;
use redis_interface::{RedisConnectionPool, RedisEntryId};
-use router_env::{instrument, tracing};
+use router_env::{
+ instrument,
+ tracing::{self, Instrument},
+};
use time::PrimitiveDateTime;
use tokio::sync::mpsc;
use uuid::Uuid;
@@ -64,7 +67,8 @@ pub async fn start_consumer<T: SchedulerAppState + 'static>(
.into_report()
.attach_printable("Failed while creating a signals handler")?;
let handle = signal.handle();
- let task_handle = tokio::spawn(common_utils::signals::signal_handler(signal, tx));
+ let task_handle =
+ tokio::spawn(common_utils::signals::signal_handler(signal, tx).in_current_span());
'consumer: loop {
match rx.try_recv() {
diff --git a/crates/scheduler/src/producer.rs b/crates/scheduler/src/producer.rs
index bcf37cdf6f2..b8081c2b9ae 100644
--- a/crates/scheduler/src/producer.rs
+++ b/crates/scheduler/src/producer.rs
@@ -3,7 +3,10 @@ use std::sync::Arc;
use common_utils::errors::CustomResult;
use diesel_models::enums::ProcessTrackerStatus;
use error_stack::{report, IntoReport, ResultExt};
-use router_env::{instrument, tracing};
+use router_env::{
+ instrument,
+ tracing::{self, Instrument},
+};
use time::Duration;
use tokio::sync::mpsc;
@@ -57,7 +60,8 @@ where
.into_report()
.attach_printable("Failed while creating a signals handler")?;
let handle = signal.handle();
- let task_handle = tokio::spawn(common_utils::signals::signal_handler(signal, tx));
+ let task_handle =
+ tokio::spawn(common_utils::signals::signal_handler(signal, tx).in_current_span());
loop {
match rx.try_recv() {
diff --git a/crates/storage_impl/src/redis.rs b/crates/storage_impl/src/redis.rs
index e4e0c021ac8..be82d4cc293 100644
--- a/crates/storage_impl/src/redis.rs
+++ b/crates/storage_impl/src/redis.rs
@@ -6,7 +6,7 @@ use std::sync::{atomic, Arc};
use error_stack::{IntoReport, ResultExt};
use redis_interface::PubsubInterface;
-use router_env::logger;
+use router_env::{logger, tracing::Instrument};
use self::{kv_store::RedisConnInterface, pub_sub::PubSubInterface};
@@ -35,9 +35,12 @@ impl RedisStore {
pub fn set_error_callback(&self, callback: tokio::sync::oneshot::Sender<()>) {
let redis_clone = self.redis_conn.clone();
- tokio::spawn(async move {
- redis_clone.on_error(callback).await;
- });
+ let _task_handle = tokio::spawn(
+ async move {
+ redis_clone.on_error(callback).await;
+ }
+ .in_current_span(),
+ );
}
pub async fn subscribe_to_channel(
@@ -54,11 +57,14 @@ impl RedisStore {
.change_context(redis_interface::errors::RedisError::SubscribeError)?;
let redis_clone = self.redis_conn.clone();
- tokio::spawn(async move {
- if let Err(e) = redis_clone.on_message().await {
- logger::error!(pubsub_err=?e);
+ let _task_handle = tokio::spawn(
+ async move {
+ if let Err(e) = redis_clone.on_message().await {
+ logger::error!(pubsub_err=?e);
+ }
}
- });
+ .in_current_span(),
+ );
Ok(())
}
}
|
2024-03-18T14:41:37Z
|
## 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 -->
Add span metadata to `tokio` spawned futures, as logs do not have parent span context. Also removed unused marco.
### 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)?
-->
Logs of save payment method. Initially the `request_id` was not available for this logs.

## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
fcfd567bfe55747dcb05c88def96373a707f8c78
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4100
|
Bug: Add Client Secret auth support for accepting PM data from Client
For an existing record in the PM table, the saved PM resources viz., Locker ID, MIT Details to be updated with client secret Auth.
|
diff --git a/crates/api_models/src/events/payment.rs b/crates/api_models/src/events/payment.rs
index b27ca142c94..b8f4a9d6d90 100644
--- a/crates/api_models/src/events/payment.rs
+++ b/crates/api_models/src/events/payment.rs
@@ -90,7 +90,7 @@ impl ApiEventMetric for PaymentMethodResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::PaymentMethod {
payment_method_id: self.payment_method_id.clone(),
- payment_method: Some(self.payment_method),
+ payment_method: self.payment_method,
payment_method_type: self.payment_method_type,
})
}
diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs
index 7eb7e213e5b..e9ff261a632 100644
--- a/crates/api_models/src/payment_methods.rs
+++ b/crates/api_models/src/payment_methods.rs
@@ -22,7 +22,7 @@ use crate::{
pub struct PaymentMethodCreate {
/// The type of payment method use for the payment.
#[schema(value_type = PaymentMethod,example = "card")]
- pub payment_method: api_enums::PaymentMethod,
+ pub payment_method: Option<api_enums::PaymentMethod>,
/// This is a sub-category of payment method.
#[schema(value_type = Option<PaymentMethodType>,example = "credit")]
@@ -65,6 +65,16 @@ pub struct PaymentMethodCreate {
#[cfg(feature = "payouts")]
#[schema(value_type = Option<Wallet>)]
pub wallet: Option<payouts::Wallet>,
+
+ /// For Client based calls, SDK will use the client_secret
+ /// in order to call /payment_methods
+ /// Client secret will be generated whenever a new
+ /// payment method is created
+ pub client_secret: Option<String>,
+
+ /// Payment method data to be passed in case of client
+ /// based flow
+ pub payment_method_data: Option<PaymentMethodCreateData>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
@@ -101,6 +111,15 @@ pub struct PaymentMethodUpdate {
pub client_secret: Option<String>,
}
+#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
+#[serde(deny_unknown_fields)]
+#[serde(rename_all = "snake_case")]
+#[serde(rename = "payment_method_data")]
+
+pub enum PaymentMethodCreateData {
+ Card(CardDetail),
+}
+
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct CardDetail {
@@ -202,7 +221,7 @@ pub struct PaymentMethodResponse {
/// The type of payment method use for the payment.
#[schema(value_type = PaymentMethod, example = "card")]
- pub payment_method: api_enums::PaymentMethod,
+ pub payment_method: Option<api_enums::PaymentMethod>,
/// This is a sub-category of payment method.
#[schema(value_type = Option<PaymentMethodType>, example = "credit")]
@@ -242,6 +261,9 @@ pub struct PaymentMethodResponse {
#[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>,
+
+ /// For Client based calls
+ pub client_secret: Option<String>,
}
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index 9dbe5f4f4bc..a5caac3fb35 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -1252,6 +1252,8 @@ pub enum PaymentMethodStatus {
/// Indicates that the payment method is awaiting some data or action before it can be marked
/// as 'active'.
Processing,
+ /// Indicates that the payment method is awaiting some data before changing state to active
+ AwaitingData,
}
impl From<AttemptStatus> for PaymentMethodStatus {
diff --git a/crates/diesel_models/src/payment_method.rs b/crates/diesel_models/src/payment_method.rs
index dbdbc78aa05..e2807f3b5ea 100644
--- a/crates/diesel_models/src/payment_method.rs
+++ b/crates/diesel_models/src/payment_method.rs
@@ -27,7 +27,7 @@ pub struct PaymentMethod {
pub direct_debit_token: Option<String>,
pub created_at: PrimitiveDateTime,
pub last_modified: PrimitiveDateTime,
- pub payment_method: storage_enums::PaymentMethod,
+ pub payment_method: Option<storage_enums::PaymentMethod>,
pub payment_method_type: Option<storage_enums::PaymentMethodType>,
pub payment_method_issuer: Option<String>,
pub payment_method_issuer_code: Option<storage_enums::PaymentMethodIssuerCode>,
@@ -39,6 +39,7 @@ pub struct PaymentMethod {
pub customer_acceptance: Option<pii::SecretSerdeValue>,
pub status: storage_enums::PaymentMethodStatus,
pub network_transaction_id: Option<String>,
+ pub client_secret: Option<String>,
}
#[derive(
@@ -49,7 +50,7 @@ pub struct PaymentMethodNew {
pub customer_id: String,
pub merchant_id: String,
pub payment_method_id: String,
- pub payment_method: storage_enums::PaymentMethod,
+ pub payment_method: Option<storage_enums::PaymentMethod>,
pub payment_method_type: Option<storage_enums::PaymentMethodType>,
pub payment_method_issuer: Option<String>,
pub payment_method_issuer_code: Option<storage_enums::PaymentMethodIssuerCode>,
@@ -73,6 +74,7 @@ pub struct PaymentMethodNew {
pub customer_acceptance: Option<pii::SecretSerdeValue>,
pub status: storage_enums::PaymentMethodStatus,
pub network_transaction_id: Option<String>,
+ pub client_secret: Option<String>,
}
impl Default for PaymentMethodNew {
@@ -84,7 +86,7 @@ impl Default for PaymentMethodNew {
merchant_id: String::default(),
payment_method_id: String::default(),
locker_id: Option::default(),
- payment_method: storage_enums::PaymentMethod::default(),
+ payment_method: Option::default(),
payment_method_type: Option::default(),
payment_method_issuer: Option::default(),
payment_method_issuer_code: Option::default(),
@@ -107,6 +109,7 @@ impl Default for PaymentMethodNew {
customer_acceptance: Option::default(),
status: storage_enums::PaymentMethodStatus::Active,
network_transaction_id: Option::default(),
+ client_secret: Option::default(),
}
}
}
@@ -135,6 +138,12 @@ pub enum PaymentMethodUpdate {
StatusUpdate {
status: Option<storage_enums::PaymentMethodStatus>,
},
+ AdditionalDataUpdate {
+ payment_method_data: Option<Encryption>,
+ status: Option<storage_enums::PaymentMethodStatus>,
+ locker_id: Option<String>,
+ payment_method: Option<storage_enums::PaymentMethod>,
+ },
ConnectorMandateDetailsUpdate {
connector_mandate_details: Option<serde_json::Value>,
},
@@ -150,6 +159,8 @@ pub struct PaymentMethodUpdateInternal {
last_used_at: Option<PrimitiveDateTime>,
network_transaction_id: Option<String>,
status: Option<storage_enums::PaymentMethodStatus>,
+ locker_id: Option<String>,
+ payment_method: Option<storage_enums::PaymentMethod>,
connector_mandate_details: Option<serde_json::Value>,
}
@@ -168,6 +179,7 @@ impl PaymentMethodUpdateInternal {
network_transaction_id,
status,
connector_mandate_details,
+ ..
} = self;
PaymentMethod {
@@ -193,6 +205,8 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
last_used_at: None,
network_transaction_id: None,
status: None,
+ locker_id: None,
+ payment_method: None,
connector_mandate_details: None,
},
PaymentMethodUpdate::PaymentMethodDataUpdate {
@@ -203,6 +217,8 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
last_used_at: None,
network_transaction_id: None,
status: None,
+ locker_id: None,
+ payment_method: None,
connector_mandate_details: None,
},
PaymentMethodUpdate::LastUsedUpdate { last_used_at } => Self {
@@ -211,6 +227,8 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
last_used_at: Some(last_used_at),
network_transaction_id: None,
status: None,
+ locker_id: None,
+ payment_method: None,
connector_mandate_details: None,
},
PaymentMethodUpdate::NetworkTransactionIdAndStatusUpdate {
@@ -222,6 +240,8 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
last_used_at: None,
network_transaction_id,
status,
+ locker_id: None,
+ payment_method: None,
connector_mandate_details: None,
},
PaymentMethodUpdate::StatusUpdate { status } => Self {
@@ -230,6 +250,23 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
last_used_at: None,
network_transaction_id: None,
status,
+ locker_id: None,
+ payment_method: None,
+ connector_mandate_details: None,
+ },
+ PaymentMethodUpdate::AdditionalDataUpdate {
+ payment_method_data,
+ status,
+ locker_id,
+ payment_method,
+ } => Self {
+ metadata: None,
+ payment_method_data,
+ last_used_at: None,
+ network_transaction_id: None,
+ status,
+ locker_id,
+ payment_method,
connector_mandate_details: None,
},
PaymentMethodUpdate::ConnectorMandateDetailsUpdate {
@@ -239,6 +276,8 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
payment_method_data: None,
last_used_at: None,
status: None,
+ locker_id: None,
+ payment_method: None,
connector_mandate_details,
network_transaction_id: None,
},
@@ -277,6 +316,7 @@ impl From<&PaymentMethodNew> for PaymentMethod {
customer_acceptance: payment_method_new.customer_acceptance.clone(),
status: payment_method_new.status,
network_transaction_id: payment_method_new.network_transaction_id.clone(),
+ client_secret: payment_method_new.client_secret.clone(),
}
}
}
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index f4255bfd737..bbe8a8060fc 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -904,7 +904,7 @@ diesel::table! {
direct_debit_token -> Nullable<Varchar>,
created_at -> Timestamp,
last_modified -> Timestamp,
- payment_method -> Varchar,
+ payment_method -> Nullable<Varchar>,
#[max_length = 64]
payment_method_type -> Nullable<Varchar>,
#[max_length = 128]
@@ -921,6 +921,8 @@ diesel::table! {
status -> Varchar,
#[max_length = 255]
network_transaction_id -> Nullable<Varchar>,
+ #[max_length = 128]
+ client_secret -> Nullable<Varchar>,
}
}
diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs
index 972dde7542a..6e9ad5848c5 100644
--- a/crates/openapi/src/openapi.rs
+++ b/crates/openapi/src/openapi.rs
@@ -206,6 +206,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payment_methods::PaymentMethodUpdate,
api_models::payment_methods::CustomerDefaultPaymentMethodResponse,
api_models::payment_methods::CardDetailFromLocker,
+ api_models::payment_methods::PaymentMethodCreateData,
api_models::payment_methods::CardDetail,
api_models::payment_methods::CardDetailUpdate,
api_models::payment_methods::RequestPaymentMethodTypes,
diff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rs
index c38167f07c4..af97c500f3e 100644
--- a/crates/router/src/core/customers.rs
+++ b/crates/router/src/core/customers.rs
@@ -223,9 +223,10 @@ pub async fn delete_customer(
)
.await
{
+ // check this in review
Ok(customer_payment_methods) => {
for pm in customer_payment_methods.into_iter() {
- if pm.payment_method == enums::PaymentMethod::Card {
+ if pm.payment_method == Some(enums::PaymentMethod::Card) {
cards::delete_card_from_locker(
&state,
&req.customer_id,
diff --git a/crates/router/src/core/locker_migration.rs b/crates/router/src/core/locker_migration.rs
index 53f503e8711..bad3b2184b5 100644
--- a/crates/router/src/core/locker_migration.rs
+++ b/crates/router/src/core/locker_migration.rs
@@ -85,7 +85,7 @@ pub async fn call_to_locker(
for pm in payment_methods
.into_iter()
- .filter(|pm| matches!(pm.payment_method, storage_enums::PaymentMethod::Card))
+ .filter(|pm| matches!(pm.payment_method, Some(storage_enums::PaymentMethod::Card)))
{
let card = cards::get_card_from_locker(
state,
@@ -128,6 +128,8 @@ pub async fn call_to_locker(
metadata: pm.metadata,
customer_id: Some(pm.customer_id),
card_network: card.card_brand,
+ client_secret: None,
+ payment_method_data: None,
};
let add_card_result = cards::add_card_hs(
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index c14042c9e62..25bb869075c 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -85,6 +85,7 @@ pub async fn create_payment_method(
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,
) -> errors::CustomResult<storage::PaymentMethod, errors::ApiErrorResponse> {
@@ -98,6 +99,11 @@ pub async fn create_payment_method(
.await
.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;
+ let client_secret = generate_id(
+ consts::ID_LENGTH,
+ format!("{payment_method_id}_secret").as_str(),
+ );
+
let response = db
.insert_payment_method(
storage::PaymentMethodNew {
@@ -113,6 +119,8 @@ pub async fn create_payment_method(
payment_method_data,
connector_mandate_details,
customer_acceptance: customer_acceptance.map(masking::Secret::new),
+ client_secret: Some(client_secret),
+ status: status.unwrap_or(enums::PaymentMethodStatus::Active),
network_transaction_id: network_transaction_id.to_owned(),
..storage::PaymentMethodNew::default()
},
@@ -122,7 +130,7 @@ pub async fn create_payment_method(
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to add payment method in db")?;
- if customer.default_payment_method_id.is_none() {
+ if customer.default_payment_method_id.is_none() && req.payment_method.is_some() {
let _ = set_default_payment_method(
db,
merchant_id.to_string(),
@@ -161,6 +169,7 @@ pub fn store_default_payment_method(
installment_payment_enabled: false, //[#219]
payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]),
last_used_at: Some(common_utils::date_time::now()),
+ client_secret: None,
};
(payment_method_response, None)
@@ -233,6 +242,253 @@ pub async fn get_or_insert_payment_method(
}
}
+#[instrument(skip_all)]
+pub async fn get_client_secret_or_add_payment_method(
+ state: routes::AppState,
+ req: api::PaymentMethodCreate,
+ merchant_account: &domain::MerchantAccount,
+ key_store: &domain::MerchantKeyStore,
+) -> errors::RouterResponse<api::PaymentMethodResponse> {
+ let db = &*state.store;
+ let merchant_id = &merchant_account.merchant_id;
+ let customer_id = req.customer_id.clone().get_required_value("customer_id")?;
+
+ #[cfg(not(feature = "payouts"))]
+ let condition = req.card.is_some();
+ #[cfg(feature = "payouts")]
+ let condition = req.card.is_some() || req.bank_transfer.is_some() || req.wallet.is_some();
+
+ if condition {
+ add_payment_method(state, req, merchant_account, key_store).await
+ } else {
+ let payment_method_id = generate_id(consts::ID_LENGTH, "pm");
+
+ let res = create_payment_method(
+ db,
+ &req,
+ customer_id.as_str(),
+ payment_method_id.as_str(),
+ None,
+ merchant_id.as_str(),
+ None,
+ None,
+ None,
+ key_store,
+ None,
+ Some(enums::PaymentMethodStatus::AwaitingData),
+ None,
+ merchant_account.storage_scheme,
+ )
+ .await?;
+
+ Ok(services::api::ApplicationResponse::Json(
+ api::PaymentMethodResponse::foreign_from(res),
+ ))
+ }
+}
+
+#[instrument(skip_all)]
+pub fn authenticate_pm_client_secret_and_check_expiry(
+ req_client_secret: &String,
+ payment_method: &diesel_models::PaymentMethod,
+) -> errors::CustomResult<bool, errors::ApiErrorResponse> {
+ let stored_client_secret = payment_method
+ .client_secret
+ .clone()
+ .get_required_value("client_secret")
+ .change_context(errors::ApiErrorResponse::MissingRequiredField {
+ field_name: "client_secret",
+ })
+ .attach_printable("client secret not found in db")?;
+
+ if req_client_secret != &stored_client_secret {
+ Err((errors::ApiErrorResponse::ClientSecretInvalid).into())
+ } else {
+ let current_timestamp = common_utils::date_time::now();
+ let session_expiry = payment_method
+ .created_at
+ .saturating_add(time::Duration::seconds(consts::DEFAULT_SESSION_EXPIRY));
+
+ let expired = current_timestamp > session_expiry;
+
+ Ok(expired)
+ }
+}
+
+#[instrument(skip_all)]
+pub async fn add_payment_method_data(
+ state: routes::AppState,
+ req: api::PaymentMethodCreate,
+ merchant_account: domain::MerchantAccount,
+ key_store: domain::MerchantKeyStore,
+ pm_id: String,
+) -> errors::RouterResponse<api::PaymentMethodResponse> {
+ let db = &*state.store;
+
+ let pmd = req
+ .payment_method_data
+ .clone()
+ .get_required_value("payment_method_data")?;
+ req.payment_method.get_required_value("payment_method")?;
+ let client_secret = req
+ .client_secret
+ .clone()
+ .get_required_value("client_secret")?;
+ let payment_method = db
+ .find_payment_method(pm_id.as_str(), merchant_account.storage_scheme)
+ .await
+ .change_context(errors::ApiErrorResponse::PaymentMethodNotFound)
+ .attach_printable("Unable to find payment method")?;
+
+ if payment_method.status != enums::PaymentMethodStatus::AwaitingData {
+ return Err((errors::ApiErrorResponse::DuplicatePaymentMethod).into());
+ }
+
+ let customer_id = payment_method.customer_id.clone();
+ let customer = db
+ .find_customer_by_customer_id_merchant_id(
+ customer_id.as_str(),
+ &merchant_account.merchant_id,
+ &key_store,
+ merchant_account.storage_scheme,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;
+
+ let client_secret_expired =
+ authenticate_pm_client_secret_and_check_expiry(&client_secret, &payment_method)?;
+
+ if client_secret_expired {
+ return Err((errors::ApiErrorResponse::ClientSecretExpired).into());
+ };
+
+ match pmd {
+ api_models::payment_methods::PaymentMethodCreateData::Card(card) => {
+ helpers::validate_card_expiry(&card.card_exp_month, &card.card_exp_year)?;
+ let resp = add_card_to_locker(
+ &state,
+ req.clone(),
+ &card,
+ &customer_id,
+ &merchant_account,
+ None,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError);
+
+ match resp {
+ Ok((mut pm_resp, duplication_check)) => {
+ if duplication_check.is_some() {
+ let pm_update = storage::PaymentMethodUpdate::StatusUpdate {
+ status: Some(enums::PaymentMethodStatus::Inactive),
+ };
+
+ db.update_payment_method(
+ payment_method,
+ pm_update,
+ merchant_account.storage_scheme,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to add payment method in db")?;
+
+ get_or_insert_payment_method(
+ db,
+ req.clone(),
+ &mut pm_resp,
+ &merchant_account,
+ &customer_id,
+ &key_store,
+ )
+ .await?;
+
+ return Ok(services::ApplicationResponse::Json(pm_resp));
+ } else {
+ let locker_id = pm_resp.payment_method_id.clone();
+ pm_resp.payment_method_id = pm_id.clone();
+ pm_resp.client_secret = Some(client_secret.clone());
+
+ let card_isin = card.card_number.clone().get_card_isin();
+
+ let card_info = db
+ .get_card_info(card_isin.as_str())
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to get card info")?;
+
+ let updated_card = CardDetailsPaymentMethod {
+ issuer_country: card_info
+ .as_ref()
+ .and_then(|ci| ci.card_issuing_country.clone()),
+ last4_digits: Some(card.card_number.clone().get_last4()),
+ expiry_month: Some(card.card_exp_month),
+ expiry_year: Some(card.card_exp_year),
+ nick_name: card.nick_name,
+ card_holder_name: card.card_holder_name,
+ card_network: card_info.as_ref().and_then(|ci| ci.card_network.clone()),
+ card_isin: Some(card_isin),
+ card_issuer: card_info.as_ref().and_then(|ci| ci.card_issuer.clone()),
+ card_type: card_info.as_ref().and_then(|ci| ci.card_type.clone()),
+ saved_to_locker: true,
+ };
+
+ let updated_pmd = Some(PaymentMethodsData::Card(updated_card));
+ let pm_data_encrypted =
+ create_encrypted_payment_method_data(&key_store, updated_pmd).await;
+
+ let pm_update = storage::PaymentMethodUpdate::AdditionalDataUpdate {
+ payment_method_data: pm_data_encrypted,
+ status: Some(enums::PaymentMethodStatus::Active),
+ locker_id: Some(locker_id),
+ payment_method: req.payment_method,
+ };
+
+ db.update_payment_method(
+ payment_method,
+ pm_update,
+ merchant_account.storage_scheme,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to add payment method in db")?;
+
+ if customer.default_payment_method_id.is_none() {
+ let _ = set_default_payment_method(
+ db,
+ merchant_account.merchant_id.clone(),
+ key_store.clone(),
+ customer_id.as_str(),
+ pm_id,
+ merchant_account.storage_scheme,
+ )
+ .await
+ .map_err(|err| logger::error!(error=?err,"Failed to set the payment method as default"));
+ }
+
+ return Ok(services::ApplicationResponse::Json(pm_resp));
+ }
+ }
+ Err(e) => {
+ let pm_update = storage::PaymentMethodUpdate::StatusUpdate {
+ status: Some(enums::PaymentMethodStatus::Inactive),
+ };
+
+ db.update_payment_method(
+ payment_method,
+ pm_update,
+ merchant_account.storage_scheme,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to update payment method in db")?;
+
+ return Err(e.attach_printable("Failed to add card to locker"));
+ }
+ }
+ }
+ }
+}
+
#[instrument(skip_all)]
pub async fn add_payment_method(
state: routes::AppState,
@@ -244,8 +500,9 @@ pub async fn add_payment_method(
let db = &*state.store;
let merchant_id = &merchant_account.merchant_id;
let customer_id = req.customer_id.clone().get_required_value("customer_id")?;
+ let payment_method = req.payment_method.get_required_value("payment_method")?;
- let response = match req.payment_method {
+ let response = match payment_method {
#[cfg(feature = "payouts")]
api_enums::PaymentMethod::BankTransfer => match req.bank_transfer.clone() {
Some(bank) => add_bank_to_locker(
@@ -402,8 +659,8 @@ pub async fn add_payment_method(
None => {
let pm_metadata = resp.metadata.as_ref().map(|data| data.peek());
- let locker_id = if resp.payment_method == api_enums::PaymentMethod::Card
- || resp.payment_method == api_enums::PaymentMethod::BankTransfer
+ let locker_id = if resp.payment_method == Some(api_enums::PaymentMethod::Card)
+ || resp.payment_method == Some(api_enums::PaymentMethod::BankTransfer)
{
Some(resp.payment_method_id)
} else {
@@ -463,6 +720,7 @@ pub async fn insert_payment_method(
pm_data_encrypted,
key_store,
connector_mandate_details,
+ None,
network_transaction_id,
storage_scheme,
)
@@ -554,6 +812,8 @@ pub async fn update_customer_payment_method(
wallet: req.wallet,
metadata: req.metadata,
customer_id: Some(pm.customer_id.clone()),
+ client_secret: None,
+ payment_method_data: None,
card_network: req
.card_network
.as_ref()
@@ -641,6 +901,7 @@ pub async fn update_customer_payment_method(
installment_payment_enabled: false,
payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]),
last_used_at: Some(common_utils::date_time::now()),
+ client_secret: None,
}
};
@@ -1602,7 +1863,7 @@ pub async fn list_payment_methods(
let customer_wallet_pm = customer_payment_methods
.iter()
.filter(|cust_pm| {
- cust_pm.payment_method == enums::PaymentMethod::Wallet
+ cust_pm.payment_method == Some(enums::PaymentMethod::Wallet)
})
.collect::<Vec<_>>();
@@ -3029,7 +3290,9 @@ pub async fn list_customer_payment_method(
for pm in resp.into_iter() {
let parent_payment_method_token = generate_id(consts::ID_LENGTH, "token");
- let payment_method_retrieval_context = match pm.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, key, state).await?;
@@ -3111,7 +3374,7 @@ pub async fn list_customer_payment_method(
};
// Retrieve the masked bank details to be sent as a response
- let bank_details = if pm.payment_method == enums::PaymentMethod::BankDebit {
+ let bank_details = if payment_method == enums::PaymentMethod::BankDebit {
get_masked_bank_details(&pm, key)
.await
.unwrap_or_else(|err| {
@@ -3128,7 +3391,7 @@ pub async fn list_customer_payment_method(
payment_token: parent_payment_method_token.to_owned(),
payment_method_id: pm.payment_method_id.clone(),
customer_id: pm.customer_id,
- payment_method: pm.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,
@@ -3432,9 +3695,14 @@ async fn get_bank_account_connector_details(
.get_required_value("payment_method_type")
.attach_printable("PaymentMethodType not found")?;
+ let pm = pm
+ .payment_method
+ .get_required_value("payment_method")
+ .attach_printable("PaymentMethod not found")?;
+
let token_data = BankAccountTokenData {
payment_method_type: pm_type,
- payment_method: pm.payment_method,
+ payment_method: pm,
connector_details: connector_details.clone(),
};
@@ -3467,6 +3735,9 @@ pub async fn set_default_payment_method(
.find_payment_method(&payment_method_id, storage_scheme)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
+ let pm = payment_method
+ .payment_method
+ .get_required_value("payment_method")?;
utils::when(
payment_method.customer_id != customer_id || payment_method.merchant_id != merchant_id,
@@ -3505,11 +3776,12 @@ pub async fn set_default_payment_method(
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update the default payment method id for the customer")?;
+
let resp = CustomerDefaultPaymentMethodResponse {
default_payment_method_id: updated_customer_details.default_payment_method_id,
customer_id,
payment_method_type: payment_method.payment_method_type,
- payment_method: payment_method.payment_method,
+ payment_method: pm,
};
Ok(services::ApplicationResponse::Json(resp))
@@ -3689,7 +3961,7 @@ pub async fn retrieve_payment_method(
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
let key = key_store.key.peek();
- let card = if pm.payment_method == enums::PaymentMethod::Card {
+ 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,
@@ -3726,6 +3998,7 @@ pub async fn retrieve_payment_method(
installment_payment_enabled: false,
payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]),
last_used_at: Some(pm.last_used_at),
+ client_secret: pm.client_secret,
},
))
}
@@ -3773,7 +4046,7 @@ pub async fn delete_payment_method(
|| Err(errors::ApiErrorResponse::PaymentMethodDeleteFailed),
)?;
- if key.payment_method == enums::PaymentMethod::Card {
+ if key.payment_method == Some(enums::PaymentMethod::Card) {
let response = delete_card_from_locker(
&state,
&key.customer_id,
diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs
index a9671cc6783..749508c9740 100644
--- a/crates/router/src/core/payment_methods/transformers.rs
+++ b/crates/router/src/core/payment_methods/transformers.rs
@@ -328,6 +328,7 @@ pub fn mk_add_bank_response_hs(
installment_payment_enabled: false, // #[#256]
payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]),
last_used_at: Some(common_utils::date_time::now()),
+ client_secret: None,
}
}
@@ -373,6 +374,7 @@ pub fn mk_add_card_response_hs(
installment_payment_enabled: false, // #[#256]
payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]),
last_used_at: Some(common_utils::date_time::now()), // [#256]
+ client_secret: None,
}
}
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index a3292e3cd69..b9a8795aa54 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -3366,7 +3366,7 @@ pub fn is_network_transaction_id_flow(
.connector_list;
pg_agnostic == "true"
- && payment_method_info.payment_method == storage_enums::PaymentMethod::Card
+ && payment_method_info.payment_method == Some(storage_enums::PaymentMethod::Card)
&& ntid_supported_connectors.contains(&connector)
&& payment_method_info.network_transaction_id.is_some()
}
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 48a6d411780..de2fdd99b7b 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -486,7 +486,7 @@ pub async fn get_token_pm_type_mandate_details(
(
None,
- Some(payment_method_info.payment_method),
+ payment_method_info.payment_method,
payment_method_info.payment_method_type,
None,
None,
@@ -635,7 +635,7 @@ pub async fn get_token_for_recurring_mandate(
merchant_connector_id: mandate.merchant_connector_id,
};
- if let diesel_models::enums::PaymentMethod::Card = payment_method.payment_method {
+ if let Some(diesel_models::enums::PaymentMethod::Card) = payment_method.payment_method {
if state.conf.locker.locker_enabled {
let _ = cards::get_lookup_key_from_locker(
state,
@@ -648,11 +648,14 @@ pub async fn get_token_for_recurring_mandate(
if let Some(payment_method_from_request) = req.payment_method {
let pm: storage_enums::PaymentMethod = payment_method_from_request;
- if pm != payment_method.payment_method {
+ if payment_method
+ .payment_method
+ .is_some_and(|payment_method| payment_method != pm)
+ {
Err(report!(errors::ApiErrorResponse::PreconditionFailed {
message:
"payment method in request does not match previously provided payment \
- method information"
+ method information"
.into()
}))?
}
@@ -660,7 +663,7 @@ pub async fn get_token_for_recurring_mandate(
Ok(MandateGenericData {
token: Some(token),
- payment_method: Some(payment_method.payment_method),
+ payment_method: payment_method.payment_method,
recurring_mandate_payment_data: Some(payments::RecurringMandatePaymentData {
payment_method_type,
original_payment_authorized_amount,
@@ -674,7 +677,7 @@ pub async fn get_token_for_recurring_mandate(
} else {
Ok(MandateGenericData {
token: None,
- payment_method: Some(payment_method.payment_method),
+ payment_method: payment_method.payment_method,
recurring_mandate_payment_data: Some(payments::RecurringMandatePaymentData {
payment_method_type,
original_payment_authorized_amount,
@@ -1264,7 +1267,7 @@ pub(crate) async fn get_payment_method_create_request(
};
let customer_id = customer.customer_id.clone();
let payment_method_request = api::PaymentMethodCreate {
- payment_method,
+ payment_method: Some(payment_method),
payment_method_type,
payment_method_issuer: card.card_issuer.clone(),
payment_method_issuer_code: None,
@@ -1279,12 +1282,14 @@ pub(crate) async fn get_payment_method_create_request(
.card_network
.as_ref()
.map(|card_network| card_network.to_string()),
+ client_secret: None,
+ payment_method_data: None,
};
Ok(payment_method_request)
}
_ => {
let payment_method_request = api::PaymentMethodCreate {
- payment_method,
+ payment_method: Some(payment_method),
payment_method_type,
payment_method_issuer: None,
payment_method_issuer_code: None,
@@ -1296,6 +1301,8 @@ pub(crate) async fn get_payment_method_create_request(
metadata: None,
customer_id: Some(customer.customer_id.to_owned()),
card_network: None,
+ client_secret: None,
+ payment_method_data: None,
};
Ok(payment_method_request)
@@ -1900,7 +1907,7 @@ pub async fn make_pm_data<'a, F: Clone, R, Ctx: PaymentMethodRetrieve>(
if payment_data.token_data.is_none() {
if let Some(payment_method_info) = &payment_data.payment_method_info {
- if payment_method_info.payment_method == storage_enums::PaymentMethod::Card {
+ if payment_method_info.payment_method == Some(storage_enums::PaymentMethod::Card) {
payment_data.token_data =
Some(storage::PaymentTokenData::PermanentCard(CardTokenData {
payment_method_id: Some(payment_method_info.payment_method_id.clone()),
diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs
index 62acfb449eb..5bf6b2e7013 100644
--- a/crates/router/src/core/payments/tokenization.rs
+++ b/crates/router/src/core/payments/tokenization.rs
@@ -306,6 +306,7 @@ where
pm_data_encrypted,
key_store,
connector_mandate_details,
+ None,
network_transaction_id,
merchant_account.storage_scheme,
)
@@ -503,11 +504,13 @@ where
None => {
let pm_metadata = create_payment_method_metadata(None, connector_token)?;
- locker_id = if resp.payment_method == PaymentMethod::Card {
- Some(resp.payment_method_id)
- } else {
- None
- };
+ locker_id = resp.payment_method.and_then(|pm| {
+ if pm == PaymentMethod::Card {
+ Some(resp.payment_method_id)
+ } else {
+ None
+ }
+ });
resp.payment_method_id = generate_id(consts::ID_LENGTH, "pm");
payment_methods::cards::create_payment_method(
@@ -522,6 +525,7 @@ where
pm_data_encrypted,
key_store,
connector_mandate_details,
+ None,
network_transaction_id,
merchant_account.storage_scheme,
)
@@ -598,6 +602,7 @@ async fn skip_saving_card_in_locker(
#[cfg(feature = "payouts")]
bank_transfer: None,
last_used_at: Some(common_utils::date_time::now()),
+ client_secret: None,
};
Ok((pm_resp, None))
@@ -619,6 +624,7 @@ async fn skip_saving_card_in_locker(
#[cfg(feature = "payouts")]
bank_transfer: None,
last_used_at: Some(common_utils::date_time::now()),
+ client_secret: None,
};
Ok((payment_method_response, None))
}
@@ -668,6 +674,7 @@ pub async fn save_in_locker(
installment_payment_enabled: false, //[#219]
payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), //[#219]
last_used_at: Some(common_utils::date_time::now()),
+ client_secret: None,
};
Ok((payment_method_response, None))
}
diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs
index 8280ddb6c2f..e521fac9a80 100644
--- a/crates/router/src/core/payouts/helpers.rs
+++ b/crates/router/src/core/payouts/helpers.rs
@@ -376,9 +376,9 @@ pub async fn save_payout_data_to_locker(
.map(|c| c.card_number.clone().get_card_isin());
let mut payment_method = api::PaymentMethodCreate {
- payment_method: api_enums::PaymentMethod::foreign_from(
+ payment_method: Some(api_enums::PaymentMethod::foreign_from(
payout_method_data.to_owned(),
- ),
+ )),
payment_method_type: Some(payment_method_type),
payment_method_issuer: None,
payment_method_issuer_code: None,
@@ -388,6 +388,8 @@ pub async fn save_payout_data_to_locker(
metadata: None,
customer_id: Some(payout_attempt.customer_id.to_owned()),
card_network: None,
+ client_secret: None,
+ payment_method_data: None,
};
let pm_data = card_isin
@@ -455,9 +457,9 @@ pub async fn save_payout_data_to_locker(
(
None,
api::PaymentMethodCreate {
- payment_method: api_enums::PaymentMethod::foreign_from(
+ payment_method: Some(api_enums::PaymentMethod::foreign_from(
payout_method_data.to_owned(),
- ),
+ )),
payment_method_type: Some(payment_method_type),
payment_method_issuer: None,
payment_method_issuer_code: None,
@@ -467,6 +469,8 @@ pub async fn save_payout_data_to_locker(
metadata: None,
customer_id: Some(payout_attempt.customer_id.to_owned()),
card_network: None,
+ client_secret: None,
+ payment_method_data: None,
},
)
};
@@ -487,6 +491,7 @@ pub async fn save_payout_data_to_locker(
key_store,
None,
None,
+ None,
merchant_account.storage_scheme,
)
.await?;
diff --git a/crates/router/src/core/pm_auth.rs b/crates/router/src/core/pm_auth.rs
index 09b8ad9f868..6d5ae7a08c3 100644
--- a/crates/router/src/core/pm_auth.rs
+++ b/crates/router/src/core/pm_auth.rs
@@ -311,7 +311,7 @@ async fn store_bank_details_in_payment_methods(
> = HashMap::new();
for pm in payment_methods {
- if pm.payment_method == enums::PaymentMethod::BankDebit {
+ if pm.payment_method == Some(enums::PaymentMethod::BankDebit) {
let bank_details_pm_data = decrypt::<serde_json::Value, masking::WithType>(
pm.payment_method_data.clone(),
key,
@@ -442,7 +442,7 @@ async fn store_bank_details_in_payment_methods(
customer_id: customer_id.clone(),
merchant_id: merchant_account.merchant_id.clone(),
payment_method_id: pm_id,
- payment_method: enums::PaymentMethod::BankDebit,
+ payment_method: Some(enums::PaymentMethod::BankDebit),
payment_method_type: Some(creds.payment_method_type),
payment_method_issuer: None,
scheme: None,
diff --git a/crates/router/src/db/payment_method.rs b/crates/router/src/db/payment_method.rs
index 72676ca81ee..528861a70aa 100644
--- a/crates/router/src/db/payment_method.rs
+++ b/crates/router/src/db/payment_method.rs
@@ -660,6 +660,7 @@ impl PaymentMethodInterface for MockDb {
connector_mandate_details: payment_method_new.connector_mandate_details,
customer_acceptance: payment_method_new.customer_acceptance,
status: payment_method_new.status,
+ client_secret: payment_method_new.client_secret,
network_transaction_id: payment_method_new.network_transaction_id,
};
payment_methods.push(payment_method.clone());
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 2771ee42947..ff660dbf7b7 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -782,6 +782,10 @@ impl PaymentMethods {
web::resource("/{payment_method_id}/update")
.route(web::post().to(payment_method_update_api)),
)
+ .service(
+ web::resource("/{payment_method_id}/save")
+ .route(web::post().to(save_payment_method_api)),
+ )
.service(
web::resource("/auth/link").route(web::post().to(pm_auth::link_token_create)),
)
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index 8e29b28fb66..aec3a5f2c1f 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -99,7 +99,8 @@ impl From<Flow> for ApiIdentifier {
| Flow::PaymentMethodsDelete
| Flow::ValidatePaymentMethod
| Flow::ListCountriesCurrencies
- | Flow::DefaultPaymentMethodsSet => Self::PaymentMethods,
+ | Flow::DefaultPaymentMethodsSet
+ | Flow::PaymentMethodSave => Self::PaymentMethods,
Flow::PmAuthLinkTokenCreate | Flow::PmAuthExchangeToken => Self::PaymentMethodAuth,
diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs
index a5ffcdabe33..e9dacd9f84f 100644
--- a/crates/router/src/routes/payment_methods.rs
+++ b/crates/router/src/routes/payment_methods.rs
@@ -23,13 +23,14 @@ pub async fn create_payment_method_api(
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(cards::add_payment_method(
+ Box::pin(cards::get_client_secret_or_add_payment_method(
state,
req,
&auth.merchant_account,
@@ -43,6 +44,41 @@ pub async fn create_payment_method_api(
.await
}
+#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodSave))]
+pub async fn save_payment_method_api(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ json_payload: web::Json<payment_methods::PaymentMethodCreate>,
+ path: web::Path<String>,
+) -> HttpResponse {
+ let flow = Flow::PaymentMethodSave;
+ let payload = json_payload.into_inner();
+ let pm_id = path.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),
+ };
+
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ payload,
+ |state, auth, req, _| {
+ Box::pin(cards::add_payment_method_data(
+ state,
+ req,
+ auth.merchant_account,
+ auth.key_store,
+ pm_id.clone(),
+ ))
+ },
+ &*auth,
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsList))]
pub async fn list_payment_method_api(
state: web::Data<AppState>,
diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs
index b04d3f3b6f6..5203b20c55b 100644
--- a/crates/router/src/services/authentication.rs
+++ b/crates/router/src/services/authentication.rs
@@ -1,5 +1,8 @@
use actix_web::http::header::HeaderMap;
-use api_models::{payment_methods::PaymentMethodListRequest, payments};
+use api_models::{
+ payment_methods::{PaymentMethodCreate, PaymentMethodListRequest},
+ payments,
+};
use async_trait::async_trait;
use common_utils::date_time;
use error_stack::{report, ResultExt};
@@ -832,6 +835,12 @@ impl ClientSecretFetch for PaymentMethodListRequest {
}
}
+impl ClientSecretFetch for PaymentMethodCreate {
+ fn get_client_secret(&self) -> Option<&String> {
+ self.client_secret.as_ref()
+ }
+}
+
impl ClientSecretFetch for api_models::cards_info::CardsInfoRequest {
fn get_client_secret(&self) -> Option<&String> {
self.client_secret.as_ref()
diff --git a/crates/router/src/types/api/mandates.rs b/crates/router/src/types/api/mandates.rs
index dda6dc0cfcc..0e80fd224da 100644
--- a/crates/router/src/types/api/mandates.rs
+++ b/crates/router/src/types/api/mandates.rs
@@ -1,5 +1,6 @@
use api_models::mandates;
pub use api_models::mandates::{MandateId, MandateResponse, MandateRevokedResponse};
+use common_utils::ext_traits::OptionExt;
use error_stack::ResultExt;
use masking::PeekInterface;
use serde::{Deserialize, Serialize};
@@ -46,7 +47,13 @@ impl MandateResponseExt for MandateResponse {
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
- let card = if payment_method.payment_method == storage_enums::PaymentMethod::Card {
+ 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(
@@ -95,7 +102,7 @@ impl MandateResponseExt for MandateResponse {
}),
card,
status: mandate.mandate_status,
- payment_method: payment_method.payment_method.to_string(),
+ payment_method: pm.to_string(),
payment_method_type,
payment_method_id: mandate.payment_method_id,
})
diff --git a/crates/router/src/types/api/payment_methods.rs b/crates/router/src/types/api/payment_methods.rs
index 13c9ec61f2a..6bf100e4d67 100644
--- a/crates/router/src/types/api/payment_methods.rs
+++ b/crates/router/src/types/api/payment_methods.rs
@@ -2,8 +2,8 @@ pub use api_models::payment_methods::{
CardDetail, CardDetailFromLocker, CardDetailsPaymentMethod, CustomerPaymentMethod,
CustomerPaymentMethodsListResponse, DefaultPaymentMethod, DeleteTokenizeByTokenRequest,
GetTokenizePayloadRequest, GetTokenizePayloadResponse, ListCountriesCurrenciesRequest,
- PaymentMethodCreate, PaymentMethodDeleteResponse, PaymentMethodId, PaymentMethodList,
- PaymentMethodListRequest, PaymentMethodListResponse, PaymentMethodResponse,
+ PaymentMethodCreate, PaymentMethodCreateData, PaymentMethodDeleteResponse, PaymentMethodId,
+ PaymentMethodList, PaymentMethodListRequest, PaymentMethodListResponse, PaymentMethodResponse,
PaymentMethodUpdate, PaymentMethodsData, TokenizePayloadEncrypted, TokenizePayloadRequest,
TokenizedCardValue1, TokenizedCardValue2, TokenizedWalletValue1, TokenizedWalletValue2,
};
@@ -21,15 +21,14 @@ pub(crate) trait PaymentMethodCreateExt {
// convert self.payment_method_type to payment_method and compare it against self.payment_method
impl PaymentMethodCreateExt for PaymentMethodCreate {
fn validate(&self) -> RouterResult<()> {
- if let Some(payment_method_type) = self.payment_method_type {
- if !validate_payment_method_type_against_payment_method(
- self.payment_method,
- payment_method_type,
- ) {
- return Err(report!(errors::ApiErrorResponse::InvalidRequestData {
- message: "Invalid 'payment_method_type' provided".to_string()
- })
- .attach_printable("Invalid payment method type"));
+ if let Some(pm) = self.payment_method {
+ if let Some(payment_method_type) = self.payment_method_type {
+ if !validate_payment_method_type_against_payment_method(pm, payment_method_type) {
+ return Err(report!(errors::ApiErrorResponse::InvalidRequestData {
+ message: "Invalid 'payment_method_type' provided".to_string()
+ })
+ .attach_printable("Invalid payment method type"));
+ }
}
}
Ok(())
diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs
index d0cd2b7a11d..6ecd53afaed 100644
--- a/crates/router/src/types/transformers.rs
+++ b/crates/router/src/types/transformers.rs
@@ -1,6 +1,9 @@
// use actix_web::HttpMessage;
use actix_web::http::header::HeaderMap;
-use api_models::{enums as api_enums, gsm as gsm_api_types, payments, routing::ConnectorSelection};
+use api_models::{
+ enums as api_enums, gsm as gsm_api_types, payment_methods, payments,
+ routing::ConnectorSelection,
+};
use common_utils::{
consts::X_HS_LATENCY,
crypto::Encryptable,
@@ -71,6 +74,28 @@ impl ForeignFrom<api_models::refunds::RefundType> for storage_enums::RefundType
}
}
+impl ForeignFrom<diesel_models::PaymentMethod> for payment_methods::PaymentMethodResponse {
+ fn foreign_from(item: diesel_models::PaymentMethod) -> Self {
+ Self {
+ merchant_id: item.merchant_id,
+ customer_id: Some(item.customer_id),
+ payment_method_id: item.payment_method_id,
+ payment_method: item.payment_method,
+ payment_method_type: item.payment_method_type,
+ card: None,
+ recurring_enabled: false,
+ installment_payment_enabled: false,
+ payment_experience: None,
+ metadata: item.metadata,
+ created: Some(item.created_at),
+ #[cfg(feature = "payouts")]
+ bank_transfer: None,
+ last_used_at: None,
+ client_secret: item.client_secret,
+ }
+ }
+}
+
impl ForeignFrom<storage_enums::AttemptStatus> for storage_enums::IntentStatus {
fn foreign_from(s: storage_enums::AttemptStatus) -> Self {
match s {
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index 991db38635b..0ec6894debe 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -113,6 +113,8 @@ pub enum Flow {
PaymentMethodsCreate,
/// Payment methods list flow.
PaymentMethodsList,
+ /// Payment method save flow
+ PaymentMethodSave,
/// Customer payment methods list flow.
CustomerPaymentMethodsList,
/// List Customers for a merchant
diff --git a/migrations/2024-03-15-133951_pm-client-secret/down.sql b/migrations/2024-03-15-133951_pm-client-secret/down.sql
new file mode 100644
index 00000000000..90b2d0dba14
--- /dev/null
+++ b/migrations/2024-03-15-133951_pm-client-secret/down.sql
@@ -0,0 +1,3 @@
+-- This file should undo anything in `up.sql`
+ALTER TABLE payment_methods DROP COLUMN IF EXISTS client_secret;
+ALTER TABLE payment_methods ALTER COLUMN payment_method SET NOT NULL;
\ No newline at end of file
diff --git a/migrations/2024-03-15-133951_pm-client-secret/up.sql b/migrations/2024-03-15-133951_pm-client-secret/up.sql
new file mode 100644
index 00000000000..e933d3ff382
--- /dev/null
+++ b/migrations/2024-03-15-133951_pm-client-secret/up.sql
@@ -0,0 +1,3 @@
+-- Your SQL goes here
+ALTER TABLE payment_methods ADD COLUMN IF NOT EXISTS client_secret VARCHAR(128) DEFAULT NULL;
+ALTER TABLE payment_methods ALTER COLUMN payment_method DROP NOT NULL;
\ No newline at end of file
diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json
index f646ba8b8d9..0bc0059e949 100644
--- a/openapi/openapi_spec.json
+++ b/openapi/openapi_spec.json
@@ -12498,10 +12498,38 @@
}
],
"nullable": true
+ },
+ "client_secret": {
+ "type": "string",
+ "description": "For Client based calls, SDK will use the client_secret\nin order to call /payment_methods\nClient secret will be generated whenever a new\npayment method is created",
+ "nullable": true
+ },
+ "payment_method_data": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/PaymentMethodCreateData"
+ }
+ ],
+ "nullable": true
}
},
"additionalProperties": false
},
+ "PaymentMethodCreateData": {
+ "oneOf": [
+ {
+ "type": "object",
+ "required": [
+ "card"
+ ],
+ "properties": {
+ "card": {
+ "$ref": "#/components/schemas/CardDetail"
+ }
+ }
+ }
+ ]
+ },
"PaymentMethodData": {
"oneOf": [
{
@@ -12887,6 +12915,11 @@
"format": "date-time",
"example": "2024-02-24T11:04:09.922Z",
"nullable": true
+ },
+ "client_secret": {
+ "type": "string",
+ "description": "For Client based calls",
+ "nullable": true
}
}
},
@@ -12895,7 +12928,8 @@
"enum": [
"active",
"inactive",
- "processing"
+ "processing",
+ "awaiting_data"
]
},
"PaymentMethodType": {
|
2024-03-19T14:34: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 -->
**Vaulting without authentication in a non-payments context.**
This PR enables -
- client_secret auth for `/payment_methods` (Generation and storage of client_secret)
- Vaulting of payment_method with client_secret auth using `/payment_methods/:pm_id/save`
- Making payment_method a nullable in schema
### Additional Changes
- [x] 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)?
-->
1. Create a customer
```
curl --location --request POST 'http://localhost:8080/customers' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_y5XDvbHKvRI6K2dAhTgXvNgQykJiqLXeYtSysCQzPGBGz3RZoUPjPcfD1LW8teYO' \
--data-raw '{
"email": "guest@example.com",
"name": "John Doe1",
"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
```
curl --location --request POST 'http://localhost:8080/payment_methods' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_63yd7Y0i2CvRcJYKfXcIE8wAva0b5YMtKHr6oTpcnggVmWqsK0Q6CvoKB1WiXoTz' \
--data-raw '{
"customer_id": "cus_RHnmMuG8mKhICwigyUeP"
}'
```
Response -
```
{
"merchant_id": "sarthak",
"customer_id": "cus_RHnmMuG8mKhICwigyUeP",
"payment_method_id": "pm_DC74n7ocq8SKGvNVai0M",
"payment_method": null,
"payment_method_type": null,
"card": null,
"recurring_enabled": false,
"installment_payment_enabled": false,
"payment_experience": null,
"metadata": null,
"created": null,
"last_used_at": null,
"client_secret": "pm_DC74n7ocq8SKGvNVai0M_secret_9wUZYKaUcORN13IdGCOo"
}
```
DB entry -
<img width="1512" alt="image" src="https://github.com/juspay/hyperswitch/assets/76486416/97359e0a-0979-4c98-844e-cb3887adfaf0">
3. Save the payment method with client_secret
```
curl --location --request POST 'http://localhost:8080/payment_methods/pm_DC74n7ocq8SKGvNVai0M/save' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: pk_dev_660e47ec672f43849d6b0403fcaf76ac' \
--data-raw '{
"payment_method": "card",
"client_secret": "pm_DC74n7ocq8SKGvNVai0M_secret_9wUZYKaUcORN13IdGCOo",
"customer_id": "cus_RHnmMuG8mKhICwigyUeP",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "10",
"card_exp_year": "2026",
"card_holder_name": "joseph"
}
}
}'
```
Response -
```
{
"merchant_id": "sarthak",
"customer_id": "cus_RHnmMuG8mKhICwigyUeP",
"payment_method_id": "pm_DC74n7ocq8SKGvNVai0M",
"payment_method": "card",
"payment_method_type": null,
"card": {
"scheme": null,
"issuer_country": null,
"last4_digits": "4242",
"expiry_month": "10",
"expiry_year": "2026",
"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-04-03T13:02:00.926Z",
"last_used_at": "2024-04-03T13:02:00.926Z",
"client_secret": "pm_DC74n7ocq8SKGvNVai0M_secret_9wUZYKaUcORN13IdGCOo"
}
```
DB entry -
<img width="1512" alt="image" src="https://github.com/juspay/hyperswitch/assets/76486416/e4eea6ea-2223-4ef9-a631-d316c8777fbe">
## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
e458e4907e39961f386900f21382c9ace3b7c392
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4105
|
Bug: Update a PM entry with connector_mandate_details when re-used in a payment
Update and store connector mandate details when an already saved card is used to make a payment and routed through a different connector
|
diff --git a/crates/diesel_models/src/payment_method.rs b/crates/diesel_models/src/payment_method.rs
index ef153c23a7b..488725f6ae8 100644
--- a/crates/diesel_models/src/payment_method.rs
+++ b/crates/diesel_models/src/payment_method.rs
@@ -126,6 +126,9 @@ pub enum PaymentMethodUpdate {
StatusUpdate {
status: Option<storage_enums::PaymentMethodStatus>,
},
+ ConnectorMandateDetailsUpdate {
+ connector_mandate_details: Option<serde_json::Value>,
+ },
}
#[derive(Clone, Debug, Default, AsChangeset, router_derive::DebugAsDisplay)]
@@ -135,6 +138,7 @@ pub struct PaymentMethodUpdateInternal {
payment_method_data: Option<Encryption>,
last_used_at: Option<PrimitiveDateTime>,
status: Option<storage_enums::PaymentMethodStatus>,
+ connector_mandate_details: Option<serde_json::Value>,
}
impl PaymentMethodUpdateInternal {
@@ -153,6 +157,7 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
payment_method_data: None,
last_used_at: None,
status: None,
+ connector_mandate_details: None,
},
PaymentMethodUpdate::PaymentMethodDataUpdate {
payment_method_data,
@@ -161,18 +166,30 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
payment_method_data,
last_used_at: None,
status: None,
+ connector_mandate_details: None,
},
PaymentMethodUpdate::LastUsedUpdate { last_used_at } => Self {
metadata: None,
payment_method_data: None,
last_used_at: Some(last_used_at),
status: None,
+ connector_mandate_details: None,
},
PaymentMethodUpdate::StatusUpdate { status } => Self {
metadata: None,
payment_method_data: None,
last_used_at: None,
status,
+ connector_mandate_details: None,
+ },
+ PaymentMethodUpdate::ConnectorMandateDetailsUpdate {
+ connector_mandate_details,
+ } => Self {
+ metadata: None,
+ payment_method_data: None,
+ last_used_at: None,
+ status: None,
+ connector_mandate_details,
},
}
}
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index 289654f93ed..3f9afe42a40 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -846,6 +846,20 @@ pub async fn update_payment_method(
Ok(())
}
+pub async fn update_payment_method_connector_mandate_details(
+ db: &dyn db::StorageInterface,
+ pm: payment_method::PaymentMethod,
+ connector_mandate_details: Option<serde_json::Value>,
+) -> errors::CustomResult<(), errors::VaultError> {
+ let pm_update = payment_method::PaymentMethodUpdate::ConnectorMandateDetailsUpdate {
+ connector_mandate_details,
+ };
+
+ db.update_payment_method(pm, pm_update)
+ .await
+ .change_context(errors::VaultError::UpdateInPaymentMethodDataTableFailed)?;
+ Ok(())
+}
#[instrument(skip_all)]
pub async fn get_card_from_hs_locker<'a>(
state: &'a routes::AppState,
diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs
index 0167f16cb8a..6b48f246673 100644
--- a/crates/router/src/core/payments/operations/payment_response.rs
+++ b/crates/router/src/core/payments/operations/payment_response.rs
@@ -19,6 +19,7 @@ use crate::{
mandate,
payment_methods::PaymentMethodRetrieve,
payments::{
+ self,
helpers::{
self as payments_helpers,
update_additional_payment_data_with_connector_response_pm_data,
@@ -880,6 +881,37 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
.in_current_span(),
);
+ let flow_name = core_utils::get_flow_name::<F>()?;
+ if flow_name == "PSync" || flow_name == "CompleteAuthorize" {
+ let connector_mandate_id = match router_data.response.clone() {
+ Ok(resp) => match resp {
+ types::PaymentsResponseData::TransactionResponse {
+ ref mandate_reference,
+ ..
+ } => {
+ if let Some(mandate_ref) = mandate_reference {
+ mandate_ref.connector_mandate_id.clone()
+ } else {
+ None
+ }
+ }
+ _ => None,
+ },
+ Err(_) => None,
+ };
+ if let Some(ref payment_method) = payment_data.payment_method_info {
+ payments::tokenization::update_connector_mandate_details_in_payment_method(
+ payment_method.clone(),
+ payment_method.payment_method_type,
+ Some(payment_data.payment_attempt.amount),
+ payment_data.payment_attempt.currency,
+ payment_data.payment_attempt.merchant_connector_id.clone(),
+ connector_mandate_id,
+ )
+ .await?;
+ }
+ }
+
// When connector requires redirection for mandate creation it can update the connector mandate_id during Psync and CompleteAuthorize
let m_db = state.clone().store;
let m_payment_method_id = payment_data.payment_attempt.payment_method_id.clone();
diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs
index 10e39b2d1b9..3941fad5a42 100644
--- a/crates/router/src/core/payments/tokenization.rs
+++ b/crates/router/src/core/payments/tokenization.rs
@@ -89,19 +89,33 @@ where
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to serialize customer acceptance to value")?;
- let connector_mandate_details = if resp.request.get_setup_mandate_details().is_none()
+ let connector_mandate_id = match responses {
+ types::PaymentsResponseData::TransactionResponse {
+ ref mandate_reference,
+ ..
+ } => {
+ if let Some(mandate_ref) = mandate_reference {
+ mandate_ref.connector_mandate_id.clone()
+ } else {
+ None
+ }
+ }
+ _ => None,
+ };
+ let check_for_mit_mandates = resp.request.get_setup_mandate_details().is_none()
&& resp
.request
.get_setup_future_usage()
.map(|future_usage| future_usage == storage_enums::FutureUsage::OffSession)
- .unwrap_or(false)
- {
+ .unwrap_or(false);
+ // insert in PaymentMethods if its a off-session mit payment
+ let connector_mandate_details = if check_for_mit_mandates {
add_connector_mandate_details_in_payment_method(
- responses,
payment_method_type,
amount,
currency,
- connector,
+ connector.merchant_connector_id.clone(),
+ connector_mandate_id.clone(),
)
} else {
None
@@ -196,7 +210,9 @@ where
)?;
if let Some(metadata) = pm_metadata {
payment_methods::cards::update_payment_method(
- db, pm, metadata,
+ db,
+ pm.clone(),
+ metadata,
)
.await
.change_context(
@@ -204,6 +220,24 @@ where
)
.attach_printable("Failed to add payment method in db")?;
};
+ // update if its a off-session mit payment
+ if check_for_mit_mandates {
+ let connector_mandate_details =
+ update_connector_mandate_details_in_payment_method(
+ pm.clone(),
+ payment_method_type,
+ amount,
+ currency,
+ connector.merchant_connector_id.clone(),
+ connector_mandate_id.clone(),
+ )
+ .await?;
+
+ payment_methods::cards::update_payment_method_connector_mandate_details(db, pm, connector_mandate_details).await.change_context(
+ errors::ApiErrorResponse::InternalServerError,
+ )
+ .attach_printable("Failed to update payment method in db")?;
+ }
}
Err(err) => {
if err.current_context().is_db_not_found() {
@@ -268,31 +302,54 @@ where
resp.payment_method_id = payment_method_id;
- let existing_pm =
- match payment_method {
- Ok(pm) => Ok(pm),
- Err(err) => {
- if err.current_context().is_db_not_found() {
- payment_methods::cards::insert_payment_method(
- db,
- &resp,
- payment_method_create_request.clone(),
- key_store,
- &merchant_account.merchant_id,
- &customer.customer_id,
- resp.metadata.clone().map(|val| val.expose()),
- customer_acceptance,
- locker_id,
- connector_mandate_details,
+ let existing_pm = match payment_method {
+ Ok(pm) => {
+ // update if its a off-session mit payment
+ if check_for_mit_mandates {
+ let connector_mandate_details =
+ update_connector_mandate_details_in_payment_method(
+ pm.clone(),
+ payment_method_type,
+ amount,
+ currency,
+ connector.merchant_connector_id.clone(),
+ connector_mandate_id.clone(),
)
- .await
- } else {
- Err(err)
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Error while finding payment method")
- }
+ .await?;
+
+ payment_methods::cards::update_payment_method_connector_mandate_details(db, pm.clone(), connector_mandate_details).await.change_context(
+ errors::ApiErrorResponse::InternalServerError,
+ )
+ .attach_printable("Failed to update payment method in db")?;
}
- }?;
+ Ok(pm)
+ }
+ Err(err) => {
+ if err.current_context().is_db_not_found() {
+ payment_methods::cards::insert_payment_method(
+ db,
+ &resp,
+ payment_method_create_request.clone(),
+ key_store,
+ &merchant_account.merchant_id,
+ &customer.customer_id,
+ resp.metadata.clone().map(|val| val.expose()),
+ customer_acceptance,
+ locker_id,
+ connector_mandate_details,
+ )
+ .await
+ } else {
+ Err(err)
+ .change_context(
+ errors::ApiErrorResponse::InternalServerError,
+ )
+ .attach_printable(
+ "Error while finding payment method",
+ )
+ }
+ }
+ }?;
payment_methods::cards::delete_card_from_locker(
state,
@@ -657,32 +714,17 @@ pub async fn add_payment_method_token<F: Clone, T: types::Tokenizable + Clone>(
}
}
-fn add_connector_mandate_details_in_payment_method(
- resp: types::PaymentsResponseData,
+pub fn add_connector_mandate_details_in_payment_method(
payment_method_type: Option<storage_enums::PaymentMethodType>,
authorized_amount: Option<i64>,
authorized_currency: Option<storage_enums::Currency>,
- connector: &api::ConnectorData,
+ merchant_connector_id: Option<String>,
+ connector_mandate_id: Option<String>,
) -> Option<storage::PaymentsMandateReference> {
let mut mandate_details = HashMap::new();
- let connector_mandate_id = match resp {
- types::PaymentsResponseData::TransactionResponse {
- mandate_reference, ..
- } => {
- if let Some(mandate_ref) = mandate_reference {
- mandate_ref.connector_mandate_id.clone()
- } else {
- None
- }
- }
- _ => None,
- };
-
- if let Some((mca_id, connector_mandate_id)) = connector
- .merchant_connector_id
- .clone()
- .zip(connector_mandate_id)
+ if let Some((mca_id, connector_mandate_id)) =
+ merchant_connector_id.clone().zip(connector_mandate_id)
{
mandate_details.insert(
mca_id,
@@ -698,3 +740,63 @@ fn add_connector_mandate_details_in_payment_method(
None
}
}
+
+pub async fn update_connector_mandate_details_in_payment_method(
+ payment_method: diesel_models::PaymentMethod,
+ payment_method_type: Option<storage_enums::PaymentMethodType>,
+ authorized_amount: Option<i64>,
+ authorized_currency: Option<storage_enums::Currency>,
+ merchant_connector_id: Option<String>,
+ connector_mandate_id: Option<String>,
+) -> RouterResult<Option<serde_json::Value>> {
+ let mandate_reference = match payment_method.connector_mandate_details {
+ Some(_) => {
+ let mandate_details = payment_method
+ .connector_mandate_details
+ .map(|val| {
+ val.parse_value::<storage::PaymentsMandateReference>("PaymentsMandateReference")
+ })
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to deserialize to Payment Mandate Reference ")?;
+
+ if let Some((mca_id, connector_mandate_id)) =
+ merchant_connector_id.clone().zip(connector_mandate_id)
+ {
+ let updated_record = storage::PaymentsMandateReferenceRecord {
+ connector_mandate_id: connector_mandate_id.clone(),
+ payment_method_type,
+ original_payment_authorized_amount: authorized_amount,
+ original_payment_authorized_currency: authorized_currency,
+ };
+ mandate_details.map(|mut payment_mandate_reference| {
+ payment_mandate_reference
+ .entry(mca_id)
+ .and_modify(|pm| *pm = updated_record)
+ .or_insert(storage::PaymentsMandateReferenceRecord {
+ connector_mandate_id,
+ payment_method_type,
+ original_payment_authorized_amount: authorized_amount,
+ original_payment_authorized_currency: authorized_currency,
+ });
+ payment_mandate_reference
+ })
+ } else {
+ None
+ }
+ }
+ None => add_connector_mandate_details_in_payment_method(
+ payment_method_type,
+ authorized_amount,
+ authorized_currency,
+ merchant_connector_id,
+ connector_mandate_id,
+ ),
+ };
+ let connector_mandate_details = mandate_reference
+ .map(|mand| mand.encode_to_value())
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to serialize customer acceptance to value")?;
+ Ok(connector_mandate_details)
+}
|
2024-03-20T11:31:15Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [x] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
The connector_mandate_details, were stored in the db earlier. In this PR if two mandates are created with two different connectors, but for same payment_method, We would update the PaymentMethod entry in the db. Also if the expiry was changed then also we would update connector_mandate_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
<!--
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 an MCA_1 with cyber source.
`Scenario 1`
- Make an off session payment
-> `Create`
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_BgXaGEnYjJ4qj7ko3kJ7Rj40BnLYhYT4IEryQ5f2HPnGJhrW59GkdRUKqHWC2jdy' \
--data-raw '{
"amount": 1000,
"currency": "USD",
"confirm": false,
"customer_id": "new-c7",
"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_eWzzcEBGyPDdSqmqr7qE/confirm' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_BgXaGEnYjJ4qj7ko3kJ7Rj40BnLYhYT4IEryQ5f2HPnGJhrW59GkdRUKqHWC2jdy' \
--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"
}}
}'
```
- A entry would be made in the connector_mandate_details with its respective mca_id
<img width="1727" alt="Screenshot 2024-03-28 at 12 55 01 PM" src="https://github.com/juspay/hyperswitch/assets/55580080/5f83c740-883b-4c53-9587-3c653fb80ef4">
`Scenario 2`
- Create an MCA_2 with cyber source for the same profile, just change the `"connector_label":"cyber source_default_2"`
-Make another off_session payment, with the same payment_method
-> `Create`
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_BgXaGEnYjJ4qj7ko3kJ7Rj40BnLYhYT4IEryQ5f2HPnGJhrW59GkdRUKqHWC2jdy' \
--data-raw '{
"amount": 1000,
"currency": "USD",
"confirm": false,
"customer_id": "new-c7",
"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_eWzzcEBGyPDdSqmqr7qE/confirm' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_BgXaGEnYjJ4qj7ko3kJ7Rj40BnLYhYT4IEryQ5f2HPnGJhrW59GkdRUKqHWC2jdy' \
--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_1GR9IUCJ08Ip7lbRMsG5"}
},
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "in sit",
"user_agent": "amet irure esse"
}}
}'
```
- A entry with updated connector_mandate_details is shown, with its respective `mca_id's`
<img width="1727" alt="Screenshot 2024-03-28 at 12 54 52 PM" src="https://github.com/juspay/hyperswitch/assets/55580080/ccda0b88-b18e-492e-9f59-43cdf7027a64">
`Scenario- 3`
- Make a payment with some Metadata-change, for eg:update the expiry number of the card`
-> `Create`
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_BgXaGEnYjJ4qj7ko3kJ7Rj40BnLYhYT4IEryQ5f2HPnGJhrW59GkdRUKqHWC2jdy' \
--data-raw '{
"amount": 1000,
"currency": "USD",
"confirm": false,
"customer_id": "new-c7",
"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_eWzzcEBGyPDdSqmqr7qE/confirm' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_BgXaGEnYjJ4qj7ko3kJ7Rj40BnLYhYT4IEryQ5f2HPnGJhrW59GkdRUKqHWC2jdy' \
--data '{
"confirm": true,
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4111111111111111",
"card_exp_month": "10",
"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"
}}
}'
```
- A updated entry of connector_mandate_id for that mca_id is shown
<img width="1727" alt="Screenshot 2024-03-28 at 12 57 01 PM" src="https://github.com/juspay/hyperswitch/assets/55580080/ba1f55d5-a06a-4170-991f-3c2863efe5b4">
`Scenario- 4`
- Make a `off_session` payment with the same card .
-> `Create`
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_BgXaGEnYjJ4qj7ko3kJ7Rj40BnLYhYT4IEryQ5f2HPnGJhrW59GkdRUKqHWC2jdy' \
--data-raw '{
"amount": 1000,
"currency": "USD",
"confirm": false,
"customer_id": "new-c7",
"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_eWzzcEBGyPDdSqmqr7qE/confirm' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_BgXaGEnYjJ4qj7ko3kJ7Rj40BnLYhYT4IEryQ5f2HPnGJhrW59GkdRUKqHWC2jdy' \
--data '{
"confirm": true,
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4111111111111111",
"card_exp_month": "10",
"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"
}}
}'
```
- The entry would be updated with the new connector_mandate_details, with the same card
<img width="1727" alt="Screenshot 2024-03-28 at 12 58 04 PM" src="https://github.com/juspay/hyperswitch/assets/55580080/4401d70b-d062-4cc5-925d-bfa2996bf344">
## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
0f8384dde996a455920bd4127c1d0ce62d5312ba
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4127
|
Bug: remove mandates from nmi collection and fix assertions in paypal
remove mandates from nmi collection and fix assertions in paypal
|
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/.meta.json
index ad1de26c594..2161cc26a05 100644
--- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/.meta.json
+++ b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/.meta.json
@@ -12,11 +12,9 @@
"Scenario8-Create a failure card payment with confirm true",
"Scenario9-Update amount with automatic capture",
"Scenario9a-Update amount with manual capture",
- "Scenario10-Create a mandate and recurring payment",
- "Scenario11-Refund recurring payment",
- "Scenario12-Add card flow",
- "Scenario13-Don't Pass CVV for save card flow and verify success payment",
- "Scenario14-Save card payment with manual capture",
- "Scenario15-Create payment without customer_id and with billing address and shipping address"
+ "Scenario10-Add card flow",
+ "Scenario11-Don't Pass CVV for save card flow and verify success payment",
+ "Scenario12-Save card payment with manual capture",
+ "Scenario13-Create payment without customer_id and with billing address and shipping address"
]
}
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/.meta.json
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/.meta.json
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/.meta.json
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Retrieve-copy/.event.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/List payment methods for a Customer/.event.meta.json
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Retrieve-copy/.event.meta.json
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/List payment methods for a Customer/.event.meta.json
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/List payment methods for a Customer/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/List payment methods for a Customer/event.test.js
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/List payment methods for a Customer/event.test.js
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/List payment methods for a Customer/event.test.js
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/List payment methods for a Customer/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/List payment methods for a Customer/request.json
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/List payment methods for a Customer/request.json
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/List payment methods for a Customer/request.json
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Create/response.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/List payment methods for a Customer/response.json
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Create/response.json
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/List payment methods for a Customer/response.json
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Create/.event.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Payments - Create/.event.meta.json
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Create/.event.meta.json
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Payments - Create/.event.meta.json
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Create/event.prerequest.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Payments - Create/event.prerequest.js
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Create/event.prerequest.js
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Payments - Create/event.prerequest.js
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Payments - Create/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Payments - Create/event.test.js
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Payments - Create/event.test.js
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Payments - Create/event.test.js
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Payments - Create/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Payments - Create/request.json
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Payments - Create/request.json
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Payments - Create/request.json
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Retrieve-copy/response.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Payments - Create/response.json
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Retrieve-copy/response.json
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Payments - Create/response.json
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Retrieve/.event.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Payments - Retrieve/.event.meta.json
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Retrieve/.event.meta.json
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Payments - Retrieve/.event.meta.json
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Payments - Retrieve/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Payments - Retrieve/event.test.js
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Payments - Retrieve/event.test.js
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Payments - Retrieve/event.test.js
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Payments - Retrieve/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Payments - Retrieve/request.json
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Payments - Retrieve/request.json
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Payments - Retrieve/request.json
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Retrieve/response.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Payments - Retrieve/response.json
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Retrieve/response.json
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Payments - Retrieve/response.json
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Recurring Payments - Create/.event.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Save card payments - Confirm/.event.meta.json
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Recurring Payments - Create/.event.meta.json
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Save card payments - Confirm/.event.meta.json
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Refunds - Create/event.prerequest.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Save card payments - Confirm/event.prerequest.js
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Refunds - Create/event.prerequest.js
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Save card payments - Confirm/event.prerequest.js
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Save card payments - Confirm/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Save card payments - Confirm/event.test.js
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Save card payments - Confirm/event.test.js
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Save card payments - Confirm/event.test.js
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Save card payments - Confirm/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Save card payments - Confirm/request.json
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Save card payments - Confirm/request.json
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Save card payments - Confirm/request.json
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Recurring Payments - Create/response.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Save card payments - Confirm/response.json
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Recurring Payments - Create/response.json
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Save card payments - Confirm/response.json
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/.event.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Save card payments - Create/.event.meta.json
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/.event.meta.json
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Save card payments - Create/.event.meta.json
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Recurring Payments - Create/event.prerequest.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Save card payments - Create/event.prerequest.js
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Recurring Payments - Create/event.prerequest.js
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Save card payments - Create/event.prerequest.js
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Save card payments - Create/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Save card payments - Create/event.test.js
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Save card payments - Create/event.test.js
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Save card payments - Create/event.test.js
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Save card payments - Create/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Save card payments - Create/request.json
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Save card payments - Create/request.json
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Save card payments - Create/request.json
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/response.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Save card payments - Create/response.json
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/response.json
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Add card flow/Save card payments - Create/response.json
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/.meta.json
deleted file mode 100644
index 28591b45430..00000000000
--- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/.meta.json
+++ /dev/null
@@ -1,8 +0,0 @@
-{
- "childrenOrder": [
- "Payments - Create",
- "Payments - Retrieve",
- "Recurring Payments - Create",
- "Payments - Retrieve-copy"
- ]
-}
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Create/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Create/event.test.js
deleted file mode 100644
index e72bc84b8cf..00000000000
--- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Create/event.test.js
+++ /dev/null
@@ -1,87 +0,0 @@
-// Validate status 2xx
-pm.test("[POST]::/payments - Status code is 2xx", function () {
- pm.response.to.be.success;
-});
-
-// Validate if response header has matching content-type
-pm.test("[POST]::/payments - 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]::/payments - Response has JSON Body", function () {
- pm.response.to.have.jsonBody();
-});
-
-// Set response object as internal variable
-let jsonData = {};
-try {
- jsonData = pm.response.json();
-} catch (e) {}
-
-// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id
-if (jsonData?.payment_id) {
- pm.collectionVariables.set("payment_id", jsonData.payment_id);
- console.log(
- "- use {{payment_id}} as collection variable for value",
- jsonData.payment_id,
- );
-} else {
- console.log(
- "INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.",
- );
-}
-
-// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id
-if (jsonData?.mandate_id) {
- pm.collectionVariables.set("mandate_id", jsonData.mandate_id);
- console.log(
- "- use {{mandate_id}} as collection variable for value",
- jsonData.mandate_id,
- );
-} else {
- console.log(
- "INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.",
- );
-}
-
-// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret
-if (jsonData?.client_secret) {
- pm.collectionVariables.set("client_secret", jsonData.client_secret);
- console.log(
- "- use {{client_secret}} as collection variable for value",
- jsonData.client_secret,
- );
-} else {
- console.log(
- "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.",
- );
-}
-
-// Response body should have value "processing" for "status"
-if (jsonData?.status) {
- pm.test(
- "[POST]::/payments - Content check if value for 'status' matches 'processing'",
- function () {
- pm.expect(jsonData.status).to.eql("processing");
- },
- );
-}
-
-// Response body should have "mandate_id"
-pm.test(
- "[POST]::/payments - Content check if 'mandate_id' exists",
- function () {
- pm.expect(typeof jsonData.mandate_id !== "undefined").to.be.true;
- },
-);
-
-// Response body should have "mandate_data"
-pm.test(
- "[POST]::/payments - Content check if 'mandate_data' exists",
- function () {
- pm.expect(typeof jsonData.mandate_data !== "undefined").to.be.true;
- },
-);
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Create/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Create/request.json
deleted file mode 100644
index c3143943700..00000000000
--- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Create/request.json
+++ /dev/null
@@ -1,109 +0,0 @@
-{
- "method": "POST",
- "header": [
- {
- "key": "Content-Type",
- "value": "application/json"
- },
- {
- "key": "Accept",
- "value": "application/json"
- }
- ],
- "body": {
- "mode": "raw",
- "options": {
- "raw": {
- "language": "json"
- }
- },
- "raw_json_formatted": {
- "amount": "{{random_number}}",
- "currency": "USD",
- "confirm": true,
- "capture_method": "automatic",
- "capture_on": "2022-09-10T10:11:12Z",
- "amount_to_capture": "{{random_number}}",
- "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://duck.com",
- "payment_method": "card",
- "payment_method_data": {
- "card": {
- "card_number": "4111111111111111",
- "card_exp_month": "10",
- "card_exp_year": "69",
- "card_holder_name": "joseph Doe",
- "card_cvc": "123"
- }
- },
- "setup_future_usage": "off_session",
- "mandate_data": {
- "customer_acceptance": {
- "acceptance_type": "offline",
- "accepted_at": "1963-05-03T04:07:52.723Z",
- "online": {
- "ip_address": "127.0.0.1",
- "user_agent": "amet irure esse"
- }
- },
- "mandate_type": {
- "single_use": {
- "amount": 100000,
- "currency": "USD"
- }
- }
- },
- "customer_acceptance": {
- "acceptance_type": "offline",
- "accepted_at": "1963-05-03T04:07:52.723Z",
- "online": {
- "ip_address": "127.0.0.1",
- "user_agent": "amet irure esse"
- }
- },
- "billing": {
- "address": {
- "line1": "1467",
- "line2": "Harrison Street",
- "line3": "Harrison Street",
- "city": "San Fransico",
- "state": "California",
- "zip": "94122",
- "country": "US",
- "first_name": "John"
- }
- },
- "shipping": {
- "address": {
- "line1": "1467",
- "line2": "Harrison Street",
- "line3": "Harrison Street",
- "city": "San Fransico",
- "state": "California",
- "zip": "94122",
- "country": "US",
- "first_name": "John"
- }
- },
- "statement_descriptor_name": "joseph",
- "statement_descriptor_suffix": "JS",
- "metadata": {
- "udf1": "value1",
- "new_customer": "true",
- "login_date": "2019-09-10T10:11:12Z"
- }
- }
- },
- "url": {
- "raw": "{{baseUrl}}/payments",
- "host": ["{{baseUrl}}"],
- "path": ["payments"]
- },
- "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
-}
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Retrieve-copy/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Retrieve-copy/event.test.js
deleted file mode 100644
index db584da2266..00000000000
--- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Retrieve-copy/event.test.js
+++ /dev/null
@@ -1,87 +0,0 @@
-// Validate status 2xx
-pm.test("[GET]::/payments/:id - Status code is 2xx", function () {
- pm.response.to.be.success;
-});
-
-// Validate if response header has matching content-type
-pm.test("[GET]::/payments/:id - 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("[GET]::/payments/:id - Response has JSON Body", function () {
- pm.response.to.have.jsonBody();
-});
-
-// Set response object as internal variable
-let jsonData = {};
-try {
- jsonData = pm.response.json();
-} catch (e) {}
-
-// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id
-if (jsonData?.payment_id) {
- pm.collectionVariables.set("payment_id", jsonData.payment_id);
- console.log(
- "- use {{payment_id}} as collection variable for value",
- jsonData.payment_id,
- );
-} else {
- console.log(
- "INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.",
- );
-}
-
-// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id
-if (jsonData?.mandate_id) {
- pm.collectionVariables.set("mandate_id", jsonData.mandate_id);
- console.log(
- "- use {{mandate_id}} as collection variable for value",
- jsonData.mandate_id,
- );
-} else {
- console.log(
- "INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.",
- );
-}
-
-// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret
-if (jsonData?.client_secret) {
- pm.collectionVariables.set("client_secret", jsonData.client_secret);
- console.log(
- "- use {{client_secret}} as collection variable for value",
- jsonData.client_secret,
- );
-} else {
- console.log(
- "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.",
- );
-}
-
-// Response body should have value "Succeeded" for "status"
-if (jsonData?.status) {
- pm.test(
- "[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'",
- function () {
- pm.expect(jsonData.status).to.eql("succeeded");
- },
- );
-}
-
-// Response body should have "mandate_id"
-pm.test(
- "[POST]::/payments - Content check if 'mandate_id' exists",
- function () {
- pm.expect(typeof jsonData.mandate_id !== "undefined").to.be.true;
- },
-);
-
-// Response body should have "mandate_data"
-pm.test(
- "[POST]::/payments - Content check if 'mandate_data' exists",
- function () {
- pm.expect(typeof jsonData.mandate_data !== "undefined").to.be.true;
- },
-);
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Retrieve/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Retrieve/event.test.js
deleted file mode 100644
index db584da2266..00000000000
--- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Retrieve/event.test.js
+++ /dev/null
@@ -1,87 +0,0 @@
-// Validate status 2xx
-pm.test("[GET]::/payments/:id - Status code is 2xx", function () {
- pm.response.to.be.success;
-});
-
-// Validate if response header has matching content-type
-pm.test("[GET]::/payments/:id - 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("[GET]::/payments/:id - Response has JSON Body", function () {
- pm.response.to.have.jsonBody();
-});
-
-// Set response object as internal variable
-let jsonData = {};
-try {
- jsonData = pm.response.json();
-} catch (e) {}
-
-// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id
-if (jsonData?.payment_id) {
- pm.collectionVariables.set("payment_id", jsonData.payment_id);
- console.log(
- "- use {{payment_id}} as collection variable for value",
- jsonData.payment_id,
- );
-} else {
- console.log(
- "INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.",
- );
-}
-
-// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id
-if (jsonData?.mandate_id) {
- pm.collectionVariables.set("mandate_id", jsonData.mandate_id);
- console.log(
- "- use {{mandate_id}} as collection variable for value",
- jsonData.mandate_id,
- );
-} else {
- console.log(
- "INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.",
- );
-}
-
-// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret
-if (jsonData?.client_secret) {
- pm.collectionVariables.set("client_secret", jsonData.client_secret);
- console.log(
- "- use {{client_secret}} as collection variable for value",
- jsonData.client_secret,
- );
-} else {
- console.log(
- "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.",
- );
-}
-
-// Response body should have value "Succeeded" for "status"
-if (jsonData?.status) {
- pm.test(
- "[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'",
- function () {
- pm.expect(jsonData.status).to.eql("succeeded");
- },
- );
-}
-
-// Response body should have "mandate_id"
-pm.test(
- "[POST]::/payments - Content check if 'mandate_id' exists",
- function () {
- pm.expect(typeof jsonData.mandate_id !== "undefined").to.be.true;
- },
-);
-
-// Response body should have "mandate_data"
-pm.test(
- "[POST]::/payments - Content check if 'mandate_data' exists",
- function () {
- pm.expect(typeof jsonData.mandate_data !== "undefined").to.be.true;
- },
-);
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Recurring Payments - Create/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Recurring Payments - Create/event.test.js
deleted file mode 100644
index ce36d5ed1d6..00000000000
--- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Recurring Payments - Create/event.test.js
+++ /dev/null
@@ -1,95 +0,0 @@
-// Validate status 2xx
-pm.test("[POST]::/payments - Status code is 2xx", function () {
- pm.response.to.be.success;
-});
-
-// Validate if response header has matching content-type
-pm.test("[POST]::/payments - 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]::/payments - Response has JSON Body", function () {
- pm.response.to.have.jsonBody();
-});
-
-// Set response object as internal variable
-let jsonData = {};
-try {
- jsonData = pm.response.json();
-} catch (e) {}
-
-// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id
-if (jsonData?.payment_id) {
- pm.collectionVariables.set("payment_id", jsonData.payment_id);
- console.log(
- "- use {{payment_id}} as collection variable for value",
- jsonData.payment_id,
- );
-} else {
- console.log(
- "INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.",
- );
-}
-
-// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id
-if (jsonData?.mandate_id) {
- pm.collectionVariables.set("mandate_id", jsonData.mandate_id);
- console.log(
- "- use {{mandate_id}} as collection variable for value",
- jsonData.mandate_id,
- );
-} else {
- console.log(
- "INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.",
- );
-}
-
-// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret
-if (jsonData?.client_secret) {
- pm.collectionVariables.set("client_secret", jsonData.client_secret);
- console.log(
- "- use {{client_secret}} as collection variable for value",
- jsonData.client_secret,
- );
-} else {
- console.log(
- "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.",
- );
-}
-
-// Response body should have value "processing" for "status"
-if (jsonData?.status) {
- pm.test(
- "[POST]::/payments - Content check if value for 'status' matches 'processing'",
- function () {
- pm.expect(jsonData.status).to.eql("processing");
- },
- );
-}
-
-// Response body should have "mandate_id"
-pm.test(
- "[POST]::/payments - Content check if 'mandate_id' exists",
- function () {
- pm.expect(typeof jsonData.mandate_id !== "undefined").to.be.true;
- },
-);
-
-// Response body should have "mandate_data"
-pm.test(
- "[POST]::/payments - Content check if 'mandate_data' exists",
- function () {
- pm.expect(typeof jsonData.mandate_data !== "undefined").to.be.true;
- },
-);
-
-// Response body should have "payment_method_data"
-pm.test(
- "[POST]::/payments - Content check if 'payment_method_data' exists",
- function () {
- pm.expect(typeof jsonData.payment_method_data !== "undefined").to.be.true;
- },
-);
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Recurring Payments - Create/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Recurring Payments - Create/request.json
deleted file mode 100644
index 44e6fbdf667..00000000000
--- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Recurring Payments - Create/request.json
+++ /dev/null
@@ -1,64 +0,0 @@
-{
- "method": "POST",
- "header": [
- {
- "key": "Content-Type",
- "value": "application/json"
- },
- {
- "key": "Accept",
- "value": "application/json"
- }
- ],
- "body": {
- "mode": "raw",
- "options": {
- "raw": {
- "language": "json"
- }
- },
- "raw_json_formatted": {
- "amount": "{{random_number}}",
- "currency": "USD",
- "confirm": true,
- "capture_method": "automatic",
- "capture_on": "2022-09-10T10:11:12Z",
- "amount_to_capture": "{{random_number}}",
- "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://duck.com",
- "mandate_id": "{{mandate_id}}",
- "off_session": true,
- "shipping": {
- "address": {
- "line1": "1467",
- "line2": "Harrison Street",
- "line3": "Harrison Street",
- "city": "San Fransico",
- "state": "California",
- "zip": "94122",
- "country": "US",
- "first_name": "John"
- }
- },
- "statement_descriptor_name": "joseph",
- "statement_descriptor_suffix": "JS",
- "metadata": {
- "udf1": "value1",
- "new_customer": "true",
- "login_date": "2019-09-10T10:11:12Z"
- }
- }
- },
- "url": {
- "raw": "{{baseUrl}}/payments",
- "host": ["{{baseUrl}}"],
- "path": ["payments"]
- },
- "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
-}
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/.meta.json
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/.meta.json
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/.meta.json
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Retrieve-copy/.event.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/List payment methods for a Customer/.event.meta.json
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Retrieve-copy/.event.meta.json
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/List payment methods for a Customer/.event.meta.json
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/List payment methods for a Customer/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/List payment methods for a Customer/event.test.js
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/List payment methods for a Customer/event.test.js
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/List payment methods for a Customer/event.test.js
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/List payment methods for a Customer/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/List payment methods for a Customer/request.json
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/List payment methods for a Customer/request.json
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/List payment methods for a Customer/request.json
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Retrieve-copy/response.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/List payment methods for a Customer/response.json
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Retrieve-copy/response.json
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/List payment methods for a Customer/response.json
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Recurring Payments - Create/.event.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/Payments - Create/.event.meta.json
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Recurring Payments - Create/.event.meta.json
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/Payments - Create/.event.meta.json
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/event.prerequest.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/Payments - Create/event.prerequest.js
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/event.prerequest.js
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/Payments - Create/event.prerequest.js
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Payments - Create/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/Payments - Create/event.test.js
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Payments - Create/event.test.js
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/Payments - Create/event.test.js
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Payments - Create/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/Payments - Create/request.json
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Payments - Create/request.json
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/Payments - Create/request.json
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Retrieve/response.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/Payments - Create/response.json
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Retrieve/response.json
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/Payments - Create/response.json
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Refunds - Create/.event.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/Save card payments - Confirm/.event.meta.json
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Refunds - Create/.event.meta.json
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/Save card payments - Confirm/.event.meta.json
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Refunds - Retrieve/event.prerequest.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/Save card payments - Confirm/event.prerequest.js
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Refunds - Retrieve/event.prerequest.js
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/Save card payments - Confirm/event.prerequest.js
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Save card payments - Confirm/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/Save card payments - Confirm/event.test.js
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Save card payments - Confirm/event.test.js
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/Save card payments - Confirm/event.test.js
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Save card payments - Confirm/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/Save card payments - Confirm/request.json
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Save card payments - Confirm/request.json
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/Save card payments - Confirm/request.json
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Recurring Payments - Create/response.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/Save card payments - Confirm/response.json
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Recurring Payments - Create/response.json
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/Save card payments - Confirm/response.json
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Refunds - Retrieve/.event.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/Save card payments - Create/.event.meta.json
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Refunds - Retrieve/.event.meta.json
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/Save card payments - Create/.event.meta.json
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Recurring Payments - Create/event.prerequest.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/Save card payments - Create/event.prerequest.js
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Recurring Payments - Create/event.prerequest.js
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/Save card payments - Create/event.prerequest.js
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Save card payments - Create/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/Save card payments - Create/event.test.js
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Save card payments - Create/event.test.js
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/Save card payments - Create/event.test.js
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Save card payments - Create/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/Save card payments - Create/request.json
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Save card payments - Create/request.json
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/Save card payments - Create/request.json
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Refunds - Create/response.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/Save card payments - Create/response.json
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Refunds - Create/response.json
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Don't Pass CVV for save card flow and verify success payment/Save card payments - Create/response.json
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/.meta.json
deleted file mode 100644
index e8b3174bc0e..00000000000
--- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/.meta.json
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "childrenOrder": [
- "Payments - Create",
- "Payments - Retrieve",
- "Recurring Payments - Create",
- "Payments - Retrieve-copy",
- "Refunds - Create",
- "Refunds - Retrieve"
- ]
-}
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/event.test.js
deleted file mode 100644
index ffa879c31d6..00000000000
--- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/event.test.js
+++ /dev/null
@@ -1,90 +0,0 @@
-// Set the environment variable 'amount' with the value from the response
-pm.environment.set("amount", pm.response.json().amount);
-
-// Validate status 2xx
-pm.test("[POST]::/payments - Status code is 2xx", function () {
- pm.response.to.be.success;
-});
-
-// Validate if response header has matching content-type
-pm.test("[POST]::/payments - 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]::/payments - Response has JSON Body", function () {
- pm.response.to.have.jsonBody();
-});
-
-// Set response object as internal variable
-let jsonData = {};
-try {
- jsonData = pm.response.json();
-} catch (e) {}
-
-// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id
-if (jsonData?.payment_id) {
- pm.collectionVariables.set("payment_id", jsonData.payment_id);
- console.log(
- "- use {{payment_id}} as collection variable for value",
- jsonData.payment_id,
- );
-} else {
- console.log(
- "INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.",
- );
-}
-
-// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id
-if (jsonData?.mandate_id) {
- pm.collectionVariables.set("mandate_id", jsonData.mandate_id);
- console.log(
- "- use {{mandate_id}} as collection variable for value",
- jsonData.mandate_id,
- );
-} else {
- console.log(
- "INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.",
- );
-}
-
-// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret
-if (jsonData?.client_secret) {
- pm.collectionVariables.set("client_secret", jsonData.client_secret);
- console.log(
- "- use {{client_secret}} as collection variable for value",
- jsonData.client_secret,
- );
-} else {
- console.log(
- "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.",
- );
-}
-
-// Response body should have value "processing" for "status"
-if (jsonData?.status) {
- pm.test(
- "[POST]::/payments - Content check if value for 'status' matches 'processing'",
- function () {
- pm.expect(jsonData.status).to.eql("processing");
- },
- );
-}
-
-// Response body should have "mandate_id"
-pm.test(
- "[POST]::/payments - Content check if 'mandate_id' exists",
- function () {
- pm.expect(typeof jsonData.mandate_id !== "undefined").to.be.true;
- },
-);
-
-// Response body should have "mandate_data"
-pm.test(
- "[POST]::/payments - Content check if 'mandate_data' exists",
- function () {
- pm.expect(typeof jsonData.mandate_data !== "undefined").to.be.true;
- },
-);
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/request.json
deleted file mode 100644
index d7511caf779..00000000000
--- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/request.json
+++ /dev/null
@@ -1,97 +0,0 @@
-{
- "method": "POST",
- "header": [
- {
- "key": "Content-Type",
- "value": "application/json"
- },
- {
- "key": "Accept",
- "value": "application/json"
- }
- ],
- "body": {
- "mode": "raw",
- "options": {
- "raw": {
- "language": "json"
- }
- },
- "raw_json_formatted": {
- "amount": "{{random_number}}",
- "currency": "USD",
- "confirm": true,
- "capture_method": "automatic",
- "capture_on": "2022-09-10T10:11:12Z",
- "amount_to_capture": "{{random_number}}",
- "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://duck.com",
- "payment_method": "card",
- "payment_method_data": {
- "card": {
- "card_number": "4111111111111111",
- "card_exp_month": "10",
- "card_exp_year": "69",
- "card_holder_name": "joseph Doe",
- "card_cvc": "123"
- }
- },
- "setup_future_usage": "off_session",
- "mandate_data": {
- "customer_acceptance": {
- "acceptance_type": "offline",
- "accepted_at": "1963-05-03T04:07:52.723Z",
- "online": {
- "ip_address": "127.0.0.1",
- "user_agent": "amet irure esse"
- }
- },
- "mandate_type": {
- "single_use": {
- "amount": 100000,
- "currency": "USD"
- }
- }
- },
- "customer_acceptance": {
- "acceptance_type": "offline",
- "accepted_at": "1963-05-03T04:07:52.723Z",
- "online": {
- "ip_address": "127.0.0.1",
- "user_agent": "amet irure esse"
- }
- },
- "shipping": {
- "address": {
- "line1": "1467",
- "line2": "Harrison Street",
- "line3": "Harrison Street",
- "city": "San Fransico",
- "state": "California",
- "zip": "94122",
- "country": "US",
- "first_name": "John"
- }
- },
- "statement_descriptor_name": "joseph",
- "statement_descriptor_suffix": "JS",
- "metadata": {
- "udf1": "value1",
- "new_customer": "true",
- "login_date": "2019-09-10T10:11:12Z"
- }
- }
- },
- "url": {
- "raw": "{{baseUrl}}/payments",
- "host": ["{{baseUrl}}"],
- "path": ["payments"]
- },
- "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
-}
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Retrieve-copy/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Retrieve-copy/event.test.js
deleted file mode 100644
index db584da2266..00000000000
--- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Retrieve-copy/event.test.js
+++ /dev/null
@@ -1,87 +0,0 @@
-// Validate status 2xx
-pm.test("[GET]::/payments/:id - Status code is 2xx", function () {
- pm.response.to.be.success;
-});
-
-// Validate if response header has matching content-type
-pm.test("[GET]::/payments/:id - 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("[GET]::/payments/:id - Response has JSON Body", function () {
- pm.response.to.have.jsonBody();
-});
-
-// Set response object as internal variable
-let jsonData = {};
-try {
- jsonData = pm.response.json();
-} catch (e) {}
-
-// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id
-if (jsonData?.payment_id) {
- pm.collectionVariables.set("payment_id", jsonData.payment_id);
- console.log(
- "- use {{payment_id}} as collection variable for value",
- jsonData.payment_id,
- );
-} else {
- console.log(
- "INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.",
- );
-}
-
-// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id
-if (jsonData?.mandate_id) {
- pm.collectionVariables.set("mandate_id", jsonData.mandate_id);
- console.log(
- "- use {{mandate_id}} as collection variable for value",
- jsonData.mandate_id,
- );
-} else {
- console.log(
- "INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.",
- );
-}
-
-// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret
-if (jsonData?.client_secret) {
- pm.collectionVariables.set("client_secret", jsonData.client_secret);
- console.log(
- "- use {{client_secret}} as collection variable for value",
- jsonData.client_secret,
- );
-} else {
- console.log(
- "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.",
- );
-}
-
-// Response body should have value "Succeeded" for "status"
-if (jsonData?.status) {
- pm.test(
- "[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'",
- function () {
- pm.expect(jsonData.status).to.eql("succeeded");
- },
- );
-}
-
-// Response body should have "mandate_id"
-pm.test(
- "[POST]::/payments - Content check if 'mandate_id' exists",
- function () {
- pm.expect(typeof jsonData.mandate_id !== "undefined").to.be.true;
- },
-);
-
-// Response body should have "mandate_data"
-pm.test(
- "[POST]::/payments - Content check if 'mandate_data' exists",
- function () {
- pm.expect(typeof jsonData.mandate_data !== "undefined").to.be.true;
- },
-);
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Retrieve/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Retrieve/event.test.js
deleted file mode 100644
index db584da2266..00000000000
--- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Retrieve/event.test.js
+++ /dev/null
@@ -1,87 +0,0 @@
-// Validate status 2xx
-pm.test("[GET]::/payments/:id - Status code is 2xx", function () {
- pm.response.to.be.success;
-});
-
-// Validate if response header has matching content-type
-pm.test("[GET]::/payments/:id - 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("[GET]::/payments/:id - Response has JSON Body", function () {
- pm.response.to.have.jsonBody();
-});
-
-// Set response object as internal variable
-let jsonData = {};
-try {
- jsonData = pm.response.json();
-} catch (e) {}
-
-// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id
-if (jsonData?.payment_id) {
- pm.collectionVariables.set("payment_id", jsonData.payment_id);
- console.log(
- "- use {{payment_id}} as collection variable for value",
- jsonData.payment_id,
- );
-} else {
- console.log(
- "INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.",
- );
-}
-
-// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id
-if (jsonData?.mandate_id) {
- pm.collectionVariables.set("mandate_id", jsonData.mandate_id);
- console.log(
- "- use {{mandate_id}} as collection variable for value",
- jsonData.mandate_id,
- );
-} else {
- console.log(
- "INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.",
- );
-}
-
-// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret
-if (jsonData?.client_secret) {
- pm.collectionVariables.set("client_secret", jsonData.client_secret);
- console.log(
- "- use {{client_secret}} as collection variable for value",
- jsonData.client_secret,
- );
-} else {
- console.log(
- "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.",
- );
-}
-
-// Response body should have value "Succeeded" for "status"
-if (jsonData?.status) {
- pm.test(
- "[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'",
- function () {
- pm.expect(jsonData.status).to.eql("succeeded");
- },
- );
-}
-
-// Response body should have "mandate_id"
-pm.test(
- "[POST]::/payments - Content check if 'mandate_id' exists",
- function () {
- pm.expect(typeof jsonData.mandate_id !== "undefined").to.be.true;
- },
-);
-
-// Response body should have "mandate_data"
-pm.test(
- "[POST]::/payments - Content check if 'mandate_data' exists",
- function () {
- pm.expect(typeof jsonData.mandate_data !== "undefined").to.be.true;
- },
-);
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Recurring Payments - Create/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Recurring Payments - Create/event.test.js
deleted file mode 100644
index 500c24ec909..00000000000
--- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Recurring Payments - Create/event.test.js
+++ /dev/null
@@ -1,98 +0,0 @@
-// Set the environment variable 'amount' with the value from the response
-pm.environment.set("amount", pm.response.json().amount);
-
-// Validate status 2xx
-pm.test("[POST]::/payments - Status code is 2xx", function () {
- pm.response.to.be.success;
-});
-
-// Validate if response header has matching content-type
-pm.test("[POST]::/payments - 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]::/payments - Response has JSON Body", function () {
- pm.response.to.have.jsonBody();
-});
-
-// Set response object as internal variable
-let jsonData = {};
-try {
- jsonData = pm.response.json();
-} catch (e) {}
-
-// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id
-if (jsonData?.payment_id) {
- pm.collectionVariables.set("payment_id", jsonData.payment_id);
- console.log(
- "- use {{payment_id}} as collection variable for value",
- jsonData.payment_id,
- );
-} else {
- console.log(
- "INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.",
- );
-}
-
-// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id
-if (jsonData?.mandate_id) {
- pm.collectionVariables.set("mandate_id", jsonData.mandate_id);
- console.log(
- "- use {{mandate_id}} as collection variable for value",
- jsonData.mandate_id,
- );
-} else {
- console.log(
- "INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.",
- );
-}
-
-// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret
-if (jsonData?.client_secret) {
- pm.collectionVariables.set("client_secret", jsonData.client_secret);
- console.log(
- "- use {{client_secret}} as collection variable for value",
- jsonData.client_secret,
- );
-} else {
- console.log(
- "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.",
- );
-}
-
-// Response body should have value "processing" for "status"
-if (jsonData?.status) {
- pm.test(
- "[POST]::/payments - Content check if value for 'status' matches 'processing'",
- function () {
- pm.expect(jsonData.status).to.eql("processing");
- },
- );
-}
-
-// Response body should have "mandate_id"
-pm.test(
- "[POST]::/payments - Content check if 'mandate_id' exists",
- function () {
- pm.expect(typeof jsonData.mandate_id !== "undefined").to.be.true;
- },
-);
-
-// Response body should have "mandate_data"
-pm.test(
- "[POST]::/payments - Content check if 'mandate_data' exists",
- function () {
- pm.expect(typeof jsonData.mandate_data !== "undefined").to.be.true;
- },
-);
-
-// Response body should have "payment_method_data"
-pm.test(
- "[POST]::/payments - Content check if 'payment_method_data' exists",
- function () {
- pm.expect(typeof jsonData.payment_method_data !== "undefined").to.be.true;
- },
-);
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Recurring Payments - Create/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Recurring Payments - Create/request.json
deleted file mode 100644
index 44e6fbdf667..00000000000
--- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Recurring Payments - Create/request.json
+++ /dev/null
@@ -1,64 +0,0 @@
-{
- "method": "POST",
- "header": [
- {
- "key": "Content-Type",
- "value": "application/json"
- },
- {
- "key": "Accept",
- "value": "application/json"
- }
- ],
- "body": {
- "mode": "raw",
- "options": {
- "raw": {
- "language": "json"
- }
- },
- "raw_json_formatted": {
- "amount": "{{random_number}}",
- "currency": "USD",
- "confirm": true,
- "capture_method": "automatic",
- "capture_on": "2022-09-10T10:11:12Z",
- "amount_to_capture": "{{random_number}}",
- "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://duck.com",
- "mandate_id": "{{mandate_id}}",
- "off_session": true,
- "shipping": {
- "address": {
- "line1": "1467",
- "line2": "Harrison Street",
- "line3": "Harrison Street",
- "city": "San Fransico",
- "state": "California",
- "zip": "94122",
- "country": "US",
- "first_name": "John"
- }
- },
- "statement_descriptor_name": "joseph",
- "statement_descriptor_suffix": "JS",
- "metadata": {
- "udf1": "value1",
- "new_customer": "true",
- "login_date": "2019-09-10T10:11:12Z"
- }
- }
- },
- "url": {
- "raw": "{{baseUrl}}/payments",
- "host": ["{{baseUrl}}"],
- "path": ["payments"]
- },
- "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
-}
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Refunds - Create/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Refunds - Create/event.test.js
deleted file mode 100644
index 85957914aa2..00000000000
--- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Refunds - Create/event.test.js
+++ /dev/null
@@ -1,53 +0,0 @@
-// Get the value of 'amount' from the environment
-const amount = pm.environment.get("amount");
-
-// Validate status 2xx
-pm.test("[POST]::/refunds - Status code is 2xx", function () {
- pm.response.to.be.success;
-});
-
-// Validate if response header has matching content-type
-pm.test("[POST]::/refunds - Content-Type is application/json", function () {
- pm.expect(pm.response.headers.get("Content-Type")).to.include(
- "application/json",
- );
-});
-
-// Set response object as internal variable
-let jsonData = {};
-try {
- jsonData = pm.response.json();
-} catch (e) {}
-
-// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id
-if (jsonData?.refund_id) {
- pm.collectionVariables.set("refund_id", jsonData.refund_id);
- console.log(
- "- use {{refund_id}} as collection variable for value",
- jsonData.refund_id,
- );
-} else {
- console.log(
- "INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.",
- );
-}
-
-// Response body should have value "pending" for "status"
-if (jsonData?.status) {
- pm.test(
- "[POST]::/refunds - Content check if value for 'status' matches 'pending'",
- function () {
- pm.expect(jsonData.status).to.eql("pending");
- },
- );
-}
-
-// Response body should have value for "amount"
-if (jsonData?.status) {
- pm.test(
- "[POST]::/refunds - Content check if value for 'amount' matches '{{amount}}'",
- function () {
- pm.expect(jsonData.amount).to.eql(amount);
- },
- );
-}
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Refunds - Create/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Refunds - Create/request.json
deleted file mode 100644
index c4e7e01345d..00000000000
--- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Refunds - Create/request.json
+++ /dev/null
@@ -1,42 +0,0 @@
-{
- "method": "POST",
- "header": [
- {
- "key": "Content-Type",
- "value": "application/json"
- },
- {
- "key": "Accept",
- "value": "application/json"
- }
- ],
- "body": {
- "mode": "raw",
- "options": {
- "raw": {
- "language": "json"
- }
- },
- "raw_json_formatted": {
- "payment_id": "{{payment_id}}",
- "amount": "{{amount}}",
- "reason": "Customer returned product",
- "refund_type": "instant",
- "metadata": {
- "udf1": "value1",
- "new_customer": "true",
- "login_date": "2019-09-10T10:11:12Z"
- }
- }
- },
- "url": {
- "raw": "{{baseUrl}}/refunds",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "refunds"
- ]
- },
- "description": "To create a refund against an already processed payment"
-}
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Refunds - Retrieve/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Refunds - Retrieve/event.test.js
deleted file mode 100644
index 1c5c9e16c6f..00000000000
--- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Refunds - Retrieve/event.test.js
+++ /dev/null
@@ -1,53 +0,0 @@
-// Get the value of 'amount' from the environment
-const refund_amount = pm.environment.get("amount");
-
-// Validate status 2xx
-pm.test("[GET]::/refunds/:id - Status code is 2xx", function () {
- pm.response.to.be.success;
-});
-
-// Validate if response header has matching content-type
-pm.test("[GET]::/refunds/:id - Content-Type is application/json", function () {
- pm.expect(pm.response.headers.get("Content-Type")).to.include(
- "application/json",
- );
-});
-
-// Set response object as internal variable
-let jsonData = {};
-try {
- jsonData = pm.response.json();
-} catch (e) {}
-
-// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id
-if (jsonData?.refund_id) {
- pm.collectionVariables.set("refund_id", jsonData.refund_id);
- console.log(
- "- use {{refund_id}} as collection variable for value",
- jsonData.refund_id,
- );
-} else {
- console.log(
- "INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.",
- );
-}
-
-// Response body should have value "succeeded" for "status"
-if (jsonData?.status) {
- pm.test(
- "[POST]::/refunds - Content check if value for 'status' matches 'succeeded'",
- function () {
- pm.expect(jsonData.status).to.eql("succeeded");
- },
- );
-}
-
-// Response body should have value for "refund_amount"
-if (jsonData?.status) {
- pm.test(
- "[POST]::/refunds - Content check if value for 'refund_amount' matches '{{refund_amount}}'",
- function () {
- pm.expect(jsonData.amount).to.eql(refund_amount);
- },
- );
-}
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Payments - Retrieve/.event.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Payments - Retrieve/.event.meta.json
deleted file mode 100644
index 688c85746ef..00000000000
--- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Payments - Retrieve/.event.meta.json
+++ /dev/null
@@ -1,5 +0,0 @@
-{
- "eventOrder": [
- "event.test.js"
- ]
-}
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/.meta.json
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/.meta.json
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/.meta.json
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Retrieve/.event.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/List payment methods for a Customer/.event.meta.json
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Retrieve/.event.meta.json
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/List payment methods for a Customer/.event.meta.json
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/List payment methods for a Customer/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/List payment methods for a Customer/event.test.js
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/List payment methods for a Customer/event.test.js
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/List payment methods for a Customer/event.test.js
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/List payment methods for a Customer/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/List payment methods for a Customer/request.json
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/List payment methods for a Customer/request.json
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/List payment methods for a Customer/request.json
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Refunds - Retrieve/response.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/List payment methods for a Customer/response.json
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Refunds - Retrieve/response.json
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/List payment methods for a Customer/response.json
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Payments - Create/.event.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Capture/.event.meta.json
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Payments - Create/.event.meta.json
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Capture/.event.meta.json
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Save card payments - Confirm/event.prerequest.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Capture/event.prerequest.js
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Save card payments - Confirm/event.prerequest.js
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Capture/event.prerequest.js
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Capture/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Capture/event.test.js
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Capture/event.test.js
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Capture/event.test.js
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Capture/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Capture/request.json
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Capture/request.json
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Capture/request.json
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/List payment methods for a Customer/response.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Capture/response.json
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/List payment methods for a Customer/response.json
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Capture/response.json
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Save card payments - Confirm/.event.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Create/.event.meta.json
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Save card payments - Confirm/.event.meta.json
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Create/.event.meta.json
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Payments - Create/event.prerequest.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Create/event.prerequest.js
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Payments - Create/event.prerequest.js
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Create/event.prerequest.js
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Create/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Create/event.test.js
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Create/event.test.js
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Create/event.test.js
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Create/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Create/request.json
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Create/request.json
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Create/request.json
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Payments - Create/response.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Create/response.json
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Payments - Create/response.json
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Create/response.json
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Save card payments - Create/.event.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Retrieve-copy-2/.event.meta.json
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Save card payments - Create/.event.meta.json
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Retrieve-copy-2/.event.meta.json
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Save card payments - Confirm/event.prerequest.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Retrieve-copy-2/event.prerequest.js
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Save card payments - Confirm/event.prerequest.js
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Retrieve-copy-2/event.prerequest.js
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve-copy-2/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Retrieve-copy-2/event.test.js
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve-copy-2/event.test.js
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Retrieve-copy-2/event.test.js
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Retrieve-copy/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Retrieve-copy-2/request.json
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Retrieve-copy/request.json
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Retrieve-copy-2/request.json
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Payments - Retrieve/response.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Retrieve-copy-2/response.json
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Payments - Retrieve/response.json
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Retrieve-copy-2/response.json
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Payments - Create/.event.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Retrieve-copy/.event.meta.json
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Payments - Create/.event.meta.json
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Retrieve-copy/.event.meta.json
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Capture/event.prerequest.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Retrieve-copy/event.prerequest.js
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Capture/event.prerequest.js
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Retrieve-copy/event.prerequest.js
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve-copy/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Retrieve-copy/event.test.js
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve-copy/event.test.js
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Retrieve-copy/event.test.js
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Retrieve/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Retrieve-copy/request.json
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Retrieve/request.json
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Retrieve-copy/request.json
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Save card payments - Confirm/response.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Retrieve-copy/response.json
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Save card payments - Confirm/response.json
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Retrieve-copy/response.json
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Save card payments - Confirm/.event.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Retrieve/.event.meta.json
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Save card payments - Confirm/.event.meta.json
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Retrieve/.event.meta.json
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve-copy-2/event.prerequest.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Retrieve/event.prerequest.js
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve-copy-2/event.prerequest.js
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Retrieve/event.prerequest.js
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Retrieve/event.test.js
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve/event.test.js
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Retrieve/event.test.js
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Retrieve-copy/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Retrieve/request.json
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Retrieve-copy/request.json
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Retrieve/request.json
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Save card payments - Create/response.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Retrieve/response.json
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Save card payments - Create/response.json
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Payments - Retrieve/response.json
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Save card payments - Create/.event.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Refunds - Create Copy/.event.meta.json
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Save card payments - Create/.event.meta.json
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Refunds - Create Copy/.event.meta.json
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve-copy/event.prerequest.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Refunds - Create Copy/event.prerequest.js
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve-copy/event.prerequest.js
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Refunds - Create Copy/event.prerequest.js
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Refunds - Create Copy/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Refunds - Create Copy/event.test.js
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Refunds - Create Copy/event.test.js
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Refunds - Create Copy/event.test.js
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Refunds - Create Copy/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Refunds - Create Copy/request.json
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Refunds - Create Copy/request.json
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Refunds - Create Copy/request.json
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/List payment methods for a Customer/response.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Refunds - Create Copy/response.json
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/List payment methods for a Customer/response.json
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Refunds - Create Copy/response.json
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Capture/.event.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Refunds - Retrieve Copy/.event.meta.json
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Capture/.event.meta.json
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Refunds - Retrieve Copy/.event.meta.json
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve/event.prerequest.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Refunds - Retrieve Copy/event.prerequest.js
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve/event.prerequest.js
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Refunds - Retrieve Copy/event.prerequest.js
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Refunds - Retrieve Copy/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Refunds - Retrieve Copy/event.test.js
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Refunds - Retrieve Copy/event.test.js
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Refunds - Retrieve Copy/event.test.js
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Refunds - Retrieve/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Refunds - Retrieve Copy/request.json
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Refunds - Retrieve/request.json
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Refunds - Retrieve Copy/request.json
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Payments - Create/response.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Refunds - Retrieve Copy/response.json
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Payments - Create/response.json
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Refunds - Retrieve Copy/response.json
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Create/.event.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Save card payments - Confirm/.event.meta.json
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Create/.event.meta.json
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Save card payments - Confirm/.event.meta.json
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Refunds - Create Copy/event.prerequest.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Save card payments - Confirm/event.prerequest.js
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Refunds - Create Copy/event.prerequest.js
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Save card payments - Confirm/event.prerequest.js
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Save card payments - Confirm/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Save card payments - Confirm/event.test.js
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Save card payments - Confirm/event.test.js
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Save card payments - Confirm/event.test.js
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Save card payments - Confirm/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Save card payments - Confirm/request.json
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Save card payments - Confirm/request.json
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Save card payments - Confirm/request.json
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Save card payments - Confirm/response.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Save card payments - Confirm/response.json
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Save card payments - Confirm/response.json
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Save card payments - Confirm/response.json
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve-copy-2/.event.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Save card payments - Create/.event.meta.json
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve-copy-2/.event.meta.json
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Save card payments - Create/.event.meta.json
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Save card payments - Create/event.prerequest.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Save card payments - Create/event.prerequest.js
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/Save card payments - Create/event.prerequest.js
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Save card payments - Create/event.prerequest.js
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Save card payments - Create/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Save card payments - Create/event.test.js
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Save card payments - Create/event.test.js
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Save card payments - Create/event.test.js
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Save card payments - Create/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Save card payments - Create/request.json
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Save card payments - Create/request.json
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Save card payments - Create/request.json
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Save card payments - Create/response.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Save card payments - Create/response.json
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Save card payments - Create/response.json
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture/Save card payments - Create/response.json
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario15-Create payment without customer_id and with billing address and shipping address/.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Create payment without customer_id and with billing address and shipping address/.meta.json
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario15-Create payment without customer_id and with billing address and shipping address/.meta.json
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Create payment without customer_id and with billing address and shipping address/.meta.json
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve-copy/.event.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Create payment without customer_id and with billing address and shipping address/Payments - Create/.event.meta.json
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve-copy/.event.meta.json
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Create payment without customer_id and with billing address and shipping address/Payments - Create/.event.meta.json
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Payments - Create/event.prerequest.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Create payment without customer_id and with billing address and shipping address/Payments - Create/event.prerequest.js
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Payments - Create/event.prerequest.js
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Create payment without customer_id and with billing address and shipping address/Payments - Create/event.prerequest.js
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario15-Create payment without customer_id and with billing address and shipping address/Payments - Create/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Create payment without customer_id and with billing address and shipping address/Payments - Create/event.test.js
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario15-Create payment without customer_id and with billing address and shipping address/Payments - Create/event.test.js
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Create payment without customer_id and with billing address and shipping address/Payments - Create/event.test.js
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario15-Create payment without customer_id and with billing address and shipping address/Payments - Create/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Create payment without customer_id and with billing address and shipping address/Payments - Create/request.json
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario15-Create payment without customer_id and with billing address and shipping address/Payments - Create/request.json
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Create payment without customer_id and with billing address and shipping address/Payments - Create/request.json
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/List payment methods for a Customer/response.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Create payment without customer_id and with billing address and shipping address/Payments - Create/response.json
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/List payment methods for a Customer/response.json
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Create payment without customer_id and with billing address and shipping address/Payments - Create/response.json
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/List payment methods for a Customer/.event.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/.event.meta.json
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario12-Add card flow/List payment methods for a Customer/.event.meta.json
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/.event.meta.json
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario15-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/event.test.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/event.test.js
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario15-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/event.test.js
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/event.test.js
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Retrieve/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/request.json
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Retrieve/request.json
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/request.json
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Capture/response.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/response.json
similarity index 100%
rename from postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Capture/response.json
rename to postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/response.json
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/List payment methods for a Customer/.event.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/List payment methods for a Customer/.event.meta.json
deleted file mode 100644
index 688c85746ef..00000000000
--- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/List payment methods for a Customer/.event.meta.json
+++ /dev/null
@@ -1,5 +0,0 @@
-{
- "eventOrder": [
- "event.test.js"
- ]
-}
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Save card payments - Create/event.prerequest.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Save card payments - Create/event.prerequest.js
deleted file mode 100644
index 30d9fbf35a0..00000000000
--- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment/Save card payments - Create/event.prerequest.js
+++ /dev/null
@@ -1 +0,0 @@
-pm.environment.set("random_number", _.random(100, 100000));
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/List payment methods for a Customer/.event.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/List payment methods for a Customer/.event.meta.json
deleted file mode 100644
index 688c85746ef..00000000000
--- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/List payment methods for a Customer/.event.meta.json
+++ /dev/null
@@ -1,5 +0,0 @@
-{
- "eventOrder": [
- "event.test.js"
- ]
-}
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Create/event.prerequest.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Create/event.prerequest.js
deleted file mode 100644
index 30d9fbf35a0..00000000000
--- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Create/event.prerequest.js
+++ /dev/null
@@ -1 +0,0 @@
-pm.environment.set("random_number", _.random(100, 100000));
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Create/response.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Create/response.json
deleted file mode 100644
index fe51488c706..00000000000
--- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Create/response.json
+++ /dev/null
@@ -1 +0,0 @@
-[]
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve-copy-2/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve-copy-2/request.json
deleted file mode 100644
index b9ebc1be4aa..00000000000
--- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve-copy-2/request.json
+++ /dev/null
@@ -1,33 +0,0 @@
-{
- "method": "GET",
- "header": [
- {
- "key": "Accept",
- "value": "application/json"
- }
- ],
- "url": {
- "raw": "{{baseUrl}}/payments/:id?force_sync=true",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments",
- ":id"
- ],
- "query": [
- {
- "key": "force_sync",
- "value": "true"
- }
- ],
- "variable": [
- {
- "key": "id",
- "value": "{{payment_id}}",
- "description": "(Required) unique payment id"
- }
- ]
- },
- "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
-}
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve-copy-2/response.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve-copy-2/response.json
deleted file mode 100644
index fe51488c706..00000000000
--- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve-copy-2/response.json
+++ /dev/null
@@ -1 +0,0 @@
-[]
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve-copy/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve-copy/request.json
deleted file mode 100644
index b9ebc1be4aa..00000000000
--- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve-copy/request.json
+++ /dev/null
@@ -1,33 +0,0 @@
-{
- "method": "GET",
- "header": [
- {
- "key": "Accept",
- "value": "application/json"
- }
- ],
- "url": {
- "raw": "{{baseUrl}}/payments/:id?force_sync=true",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments",
- ":id"
- ],
- "query": [
- {
- "key": "force_sync",
- "value": "true"
- }
- ],
- "variable": [
- {
- "key": "id",
- "value": "{{payment_id}}",
- "description": "(Required) unique payment id"
- }
- ]
- },
- "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
-}
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve-copy/response.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve-copy/response.json
deleted file mode 100644
index fe51488c706..00000000000
--- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve-copy/response.json
+++ /dev/null
@@ -1 +0,0 @@
-[]
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve/.event.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve/.event.meta.json
deleted file mode 100644
index eb871bbcb9b..00000000000
--- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve/.event.meta.json
+++ /dev/null
@@ -1,3 +0,0 @@
-{
- "eventOrder": ["event.prerequest.js", "event.test.js"]
-}
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve/request.json
deleted file mode 100644
index b9ebc1be4aa..00000000000
--- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve/request.json
+++ /dev/null
@@ -1,33 +0,0 @@
-{
- "method": "GET",
- "header": [
- {
- "key": "Accept",
- "value": "application/json"
- }
- ],
- "url": {
- "raw": "{{baseUrl}}/payments/:id?force_sync=true",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments",
- ":id"
- ],
- "query": [
- {
- "key": "force_sync",
- "value": "true"
- }
- ],
- "variable": [
- {
- "key": "id",
- "value": "{{payment_id}}",
- "description": "(Required) unique payment id"
- }
- ]
- },
- "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
-}
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve/response.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve/response.json
deleted file mode 100644
index fe51488c706..00000000000
--- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Retrieve/response.json
+++ /dev/null
@@ -1 +0,0 @@
-[]
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Refunds - Create Copy/.event.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Refunds - Create Copy/.event.meta.json
deleted file mode 100644
index eb871bbcb9b..00000000000
--- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Refunds - Create Copy/.event.meta.json
+++ /dev/null
@@ -1,3 +0,0 @@
-{
- "eventOrder": ["event.prerequest.js", "event.test.js"]
-}
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Refunds - Create Copy/response.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Refunds - Create Copy/response.json
deleted file mode 100644
index fe51488c706..00000000000
--- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Refunds - Create Copy/response.json
+++ /dev/null
@@ -1 +0,0 @@
-[]
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Refunds - Retrieve Copy/.event.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Refunds - Retrieve Copy/.event.meta.json
deleted file mode 100644
index eb871bbcb9b..00000000000
--- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Refunds - Retrieve Copy/.event.meta.json
+++ /dev/null
@@ -1,3 +0,0 @@
-{
- "eventOrder": ["event.prerequest.js", "event.test.js"]
-}
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Refunds - Retrieve Copy/event.prerequest.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Refunds - Retrieve Copy/event.prerequest.js
deleted file mode 100644
index e69de29bb2d..00000000000
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Refunds - Retrieve Copy/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Refunds - Retrieve Copy/request.json
deleted file mode 100644
index 6c28619e856..00000000000
--- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Refunds - Retrieve Copy/request.json
+++ /dev/null
@@ -1,27 +0,0 @@
-{
- "method": "GET",
- "header": [
- {
- "key": "Accept",
- "value": "application/json"
- }
- ],
- "url": {
- "raw": "{{baseUrl}}/refunds/:id",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "refunds",
- ":id"
- ],
- "variable": [
- {
- "key": "id",
- "value": "{{refund_id}}",
- "description": "(Required) unique refund id"
- }
- ]
- },
- "description": "To retrieve the properties of a Refund. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
-}
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Refunds - Retrieve Copy/response.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Refunds - Retrieve Copy/response.json
deleted file mode 100644
index fe51488c706..00000000000
--- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Refunds - Retrieve Copy/response.json
+++ /dev/null
@@ -1 +0,0 @@
-[]
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Save card payments - Confirm/.event.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Save card payments - Confirm/.event.meta.json
deleted file mode 100644
index eb871bbcb9b..00000000000
--- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Save card payments - Confirm/.event.meta.json
+++ /dev/null
@@ -1,3 +0,0 @@
-{
- "eventOrder": ["event.prerequest.js", "event.test.js"]
-}
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Save card payments - Confirm/event.prerequest.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Save card payments - Confirm/event.prerequest.js
deleted file mode 100644
index e69de29bb2d..00000000000
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Save card payments - Confirm/response.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Save card payments - Confirm/response.json
deleted file mode 100644
index fe51488c706..00000000000
--- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Save card payments - Confirm/response.json
+++ /dev/null
@@ -1 +0,0 @@
-[]
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Save card payments - Create/.event.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Save card payments - Create/.event.meta.json
deleted file mode 100644
index eb871bbcb9b..00000000000
--- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Save card payments - Create/.event.meta.json
+++ /dev/null
@@ -1,3 +0,0 @@
-{
- "eventOrder": ["event.prerequest.js", "event.test.js"]
-}
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Save card payments - Create/event.prerequest.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Save card payments - Create/event.prerequest.js
deleted file mode 100644
index 30d9fbf35a0..00000000000
--- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Save card payments - Create/event.prerequest.js
+++ /dev/null
@@ -1 +0,0 @@
-pm.environment.set("random_number", _.random(100, 100000));
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Save card payments - Create/response.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Save card payments - Create/response.json
deleted file mode 100644
index fe51488c706..00000000000
--- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Save card payments - Create/response.json
+++ /dev/null
@@ -1 +0,0 @@
-[]
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario15-Create payment without customer_id and with billing address and shipping address/Payments - Create/.event.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario15-Create payment without customer_id and with billing address and shipping address/Payments - Create/.event.meta.json
deleted file mode 100644
index eb871bbcb9b..00000000000
--- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario15-Create payment without customer_id and with billing address and shipping address/Payments - Create/.event.meta.json
+++ /dev/null
@@ -1,3 +0,0 @@
-{
- "eventOrder": ["event.prerequest.js", "event.test.js"]
-}
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario15-Create payment without customer_id and with billing address and shipping address/Payments - Create/event.prerequest.js b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario15-Create payment without customer_id and with billing address and shipping address/Payments - Create/event.prerequest.js
deleted file mode 100644
index 30d9fbf35a0..00000000000
--- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario15-Create payment without customer_id and with billing address and shipping address/Payments - Create/event.prerequest.js
+++ /dev/null
@@ -1 +0,0 @@
-pm.environment.set("random_number", _.random(100, 100000));
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario15-Create payment without customer_id and with billing address and shipping address/Payments - Create/response.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario15-Create payment without customer_id and with billing address and shipping address/Payments - Create/response.json
deleted file mode 100644
index fe51488c706..00000000000
--- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario15-Create payment without customer_id and with billing address and shipping address/Payments - Create/response.json
+++ /dev/null
@@ -1 +0,0 @@
-[]
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario15-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/.event.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario15-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/.event.meta.json
deleted file mode 100644
index 688c85746ef..00000000000
--- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario15-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/.event.meta.json
+++ /dev/null
@@ -1,5 +0,0 @@
-{
- "eventOrder": [
- "event.test.js"
- ]
-}
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario15-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario15-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/request.json
deleted file mode 100644
index b9ebc1be4aa..00000000000
--- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario15-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/request.json
+++ /dev/null
@@ -1,33 +0,0 @@
-{
- "method": "GET",
- "header": [
- {
- "key": "Accept",
- "value": "application/json"
- }
- ],
- "url": {
- "raw": "{{baseUrl}}/payments/:id?force_sync=true",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments",
- ":id"
- ],
- "query": [
- {
- "key": "force_sync",
- "value": "true"
- }
- ],
- "variable": [
- {
- "key": "id",
- "value": "{{payment_id}}",
- "description": "(Required) unique payment id"
- }
- ]
- },
- "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
-}
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario15-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/response.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario15-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/response.json
deleted file mode 100644
index fe51488c706..00000000000
--- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario15-Create payment without customer_id and with billing address and shipping address/Payments - Retrieve/response.json
+++ /dev/null
@@ -1 +0,0 @@
-[]
diff --git a/postman/collection-dir/paypal/Flow Testcases/Variation Cases/Scenario1-Create payment with Invalid card details/Payments - Create(Invalid card number)/event.test.js b/postman/collection-dir/paypal/Flow Testcases/Variation Cases/Scenario1-Create payment with Invalid card details/Payments - Create(Invalid card number)/event.test.js
index 57900d52342..1de22fee9be 100644
--- a/postman/collection-dir/paypal/Flow Testcases/Variation Cases/Scenario1-Create payment with Invalid card details/Payments - Create(Invalid card number)/event.test.js
+++ b/postman/collection-dir/paypal/Flow Testcases/Variation Cases/Scenario1-Create payment with Invalid card details/Payments - Create(Invalid card number)/event.test.js
@@ -18,7 +18,7 @@ pm.test("[POST]::/payments - Response has JSON Body", function () {
let jsonData = {};
try {
jsonData = pm.response.json();
-} catch (e) {}
+} catch (e) { }
// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id
if (jsonData?.payment_id) {
@@ -72,9 +72,9 @@ if (jsonData?.status) {
// Response body should have value "requires_confirmation" for "status"
if (jsonData?.status) {
pm.test(
- "[POST]::/payments - Content check if value for 'error_code' matches 'UNPROCESSABLE_ENTITY'",
+ "[POST]::/payments - Content check if value for 'error_code' matches 'VALIDATION_ERROR'",
function () {
- pm.expect(jsonData.error_code).to.eql("UNPROCESSABLE_ENTITY");
+ pm.expect(jsonData.error_code).to.eql("VALIDATION_ERROR");
},
);
}
diff --git a/postman/collection-json/nmi.postman_collection.json b/postman/collection-json/nmi.postman_collection.json
index fa1dbac954f..ab493bc92ba 100644
--- a/postman/collection-json/nmi.postman_collection.json
+++ b/postman/collection-json/nmi.postman_collection.json
@@ -6504,1368 +6504,7 @@
]
},
{
- "name": "Scenario10-Create a mandate and recurring payment",
- "item": [
- {
- "name": "Payments - Create",
- "event": [
- {
- "listen": "prerequest",
- "script": {
- "exec": [
- "pm.environment.set(\"random_number\", _.random(100, 100000));",
- ""
- ],
- "type": "text/javascript"
- }
- },
- {
- "listen": "test",
- "script": {
- "exec": [
- "// Validate status 2xx",
- "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
- "});",
- "",
- "// Validate if response header has matching content-type",
- "pm.test(\"[POST]::/payments - 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]::/payments - Response has JSON Body\", function () {",
- " pm.response.to.have.jsonBody();",
- "});",
- "",
- "// Set response object as internal variable",
- "let jsonData = {};",
- "try {",
- " jsonData = pm.response.json();",
- "} catch (e) {}",
- "",
- "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
- "if (jsonData?.payment_id) {",
- " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
- " console.log(",
- " \"- use {{payment_id}} as collection variable for value\",",
- " jsonData.payment_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
- " );",
- "}",
- "",
- "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
- "if (jsonData?.mandate_id) {",
- " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
- " console.log(",
- " \"- use {{mandate_id}} as collection variable for value\",",
- " jsonData.mandate_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
- " );",
- "}",
- "",
- "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
- "if (jsonData?.client_secret) {",
- " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
- " console.log(",
- " \"- use {{client_secret}} as collection variable for value\",",
- " jsonData.client_secret,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
- " );",
- "}",
- "",
- "// Response body should have value \"processing\" for \"status\"",
- "if (jsonData?.status) {",
- " pm.test(",
- " \"[POST]::/payments - Content check if value for 'status' matches 'processing'\",",
- " function () {",
- " pm.expect(jsonData.status).to.eql(\"processing\");",
- " },",
- " );",
- "}",
- "",
- "// Response body should have \"mandate_id\"",
- "pm.test(",
- " \"[POST]::/payments - Content check if 'mandate_id' exists\",",
- " function () {",
- " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;",
- " },",
- ");",
- "",
- "// Response body should have \"mandate_data\"",
- "pm.test(",
- " \"[POST]::/payments - Content check if 'mandate_data' exists\",",
- " function () {",
- " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;",
- " },",
- ");",
- ""
- ],
- "type": "text/javascript"
- }
- }
- ],
- "request": {
- "method": "POST",
- "header": [
- {
- "key": "Content-Type",
- "value": "application/json"
- },
- {
- "key": "Accept",
- "value": "application/json"
- }
- ],
- "body": {
- "mode": "raw",
- "options": {
- "raw": {
- "language": "json"
- }
- },
- "raw": "{\"amount\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"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://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4111111111111111\",\"card_exp_month\":\"10\",\"card_exp_year\":\"69\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"setup_future_usage\":\"off_session\",\"mandate_data\":{\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"127.0.0.1\",\"user_agent\":\"amet irure esse\"}},\"mandate_type\":{\"single_use\":{\"amount\":100000,\"currency\":\"USD\"}}},\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"127.0.0.1\",\"user_agent\":\"amet irure esse\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
- },
- "url": {
- "raw": "{{baseUrl}}/payments",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments"
- ]
- },
- "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
- },
- "response": []
- },
- {
- "name": "Payments - Retrieve",
- "event": [
- {
- "listen": "test",
- "script": {
- "exec": [
- "// Validate status 2xx",
- "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
- "});",
- "",
- "// Validate if response header has matching content-type",
- "pm.test(\"[GET]::/payments/:id - 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(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
- " pm.response.to.have.jsonBody();",
- "});",
- "",
- "// Set response object as internal variable",
- "let jsonData = {};",
- "try {",
- " jsonData = pm.response.json();",
- "} catch (e) {}",
- "",
- "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
- "if (jsonData?.payment_id) {",
- " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
- " console.log(",
- " \"- use {{payment_id}} as collection variable for value\",",
- " jsonData.payment_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
- " );",
- "}",
- "",
- "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
- "if (jsonData?.mandate_id) {",
- " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
- " console.log(",
- " \"- use {{mandate_id}} as collection variable for value\",",
- " jsonData.mandate_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
- " );",
- "}",
- "",
- "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
- "if (jsonData?.client_secret) {",
- " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
- " console.log(",
- " \"- use {{client_secret}} as collection variable for value\",",
- " jsonData.client_secret,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
- " );",
- "}",
- "",
- "// Response body should have value \"Succeeded\" for \"status\"",
- "if (jsonData?.status) {",
- " pm.test(",
- " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",",
- " function () {",
- " pm.expect(jsonData.status).to.eql(\"succeeded\");",
- " },",
- " );",
- "}",
- "",
- "// Response body should have \"mandate_id\"",
- "pm.test(",
- " \"[POST]::/payments - Content check if 'mandate_id' exists\",",
- " function () {",
- " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;",
- " },",
- ");",
- "",
- "// Response body should have \"mandate_data\"",
- "pm.test(",
- " \"[POST]::/payments - Content check if 'mandate_data' exists\",",
- " function () {",
- " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;",
- " },",
- ");",
- ""
- ],
- "type": "text/javascript"
- }
- }
- ],
- "request": {
- "method": "GET",
- "header": [
- {
- "key": "Accept",
- "value": "application/json"
- }
- ],
- "url": {
- "raw": "{{baseUrl}}/payments/:id?force_sync=true",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments",
- ":id"
- ],
- "query": [
- {
- "key": "force_sync",
- "value": "true"
- }
- ],
- "variable": [
- {
- "key": "id",
- "value": "{{payment_id}}",
- "description": "(Required) unique payment id"
- }
- ]
- },
- "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
- },
- "response": []
- },
- {
- "name": "Recurring Payments - Create",
- "event": [
- {
- "listen": "prerequest",
- "script": {
- "exec": [
- "pm.environment.set(\"random_number\", _.random(100, 100000));",
- ""
- ],
- "type": "text/javascript"
- }
- },
- {
- "listen": "test",
- "script": {
- "exec": [
- "// Validate status 2xx",
- "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
- "});",
- "",
- "// Validate if response header has matching content-type",
- "pm.test(\"[POST]::/payments - 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]::/payments - Response has JSON Body\", function () {",
- " pm.response.to.have.jsonBody();",
- "});",
- "",
- "// Set response object as internal variable",
- "let jsonData = {};",
- "try {",
- " jsonData = pm.response.json();",
- "} catch (e) {}",
- "",
- "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
- "if (jsonData?.payment_id) {",
- " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
- " console.log(",
- " \"- use {{payment_id}} as collection variable for value\",",
- " jsonData.payment_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
- " );",
- "}",
- "",
- "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
- "if (jsonData?.mandate_id) {",
- " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
- " console.log(",
- " \"- use {{mandate_id}} as collection variable for value\",",
- " jsonData.mandate_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
- " );",
- "}",
- "",
- "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
- "if (jsonData?.client_secret) {",
- " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
- " console.log(",
- " \"- use {{client_secret}} as collection variable for value\",",
- " jsonData.client_secret,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
- " );",
- "}",
- "",
- "// Response body should have value \"processing\" for \"status\"",
- "if (jsonData?.status) {",
- " pm.test(",
- " \"[POST]::/payments - Content check if value for 'status' matches 'processing'\",",
- " function () {",
- " pm.expect(jsonData.status).to.eql(\"processing\");",
- " },",
- " );",
- "}",
- "",
- "// Response body should have \"mandate_id\"",
- "pm.test(",
- " \"[POST]::/payments - Content check if 'mandate_id' exists\",",
- " function () {",
- " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;",
- " },",
- ");",
- "",
- "// Response body should have \"mandate_data\"",
- "pm.test(",
- " \"[POST]::/payments - Content check if 'mandate_data' exists\",",
- " function () {",
- " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;",
- " },",
- ");",
- "",
- "// Response body should have \"payment_method_data\"",
- "pm.test(",
- " \"[POST]::/payments - Content check if 'payment_method_data' exists\",",
- " function () {",
- " pm.expect(typeof jsonData.payment_method_data !== \"undefined\").to.be.true;",
- " },",
- ");",
- ""
- ],
- "type": "text/javascript"
- }
- }
- ],
- "request": {
- "method": "POST",
- "header": [
- {
- "key": "Content-Type",
- "value": "application/json"
- },
- {
- "key": "Accept",
- "value": "application/json"
- }
- ],
- "body": {
- "mode": "raw",
- "options": {
- "raw": {
- "language": "json"
- }
- },
- "raw": "{\"amount\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"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://duck.com\",\"mandate_id\":\"{{mandate_id}}\",\"off_session\":true,\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
- },
- "url": {
- "raw": "{{baseUrl}}/payments",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments"
- ]
- },
- "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
- },
- "response": []
- },
- {
- "name": "Payments - Retrieve-copy",
- "event": [
- {
- "listen": "test",
- "script": {
- "exec": [
- "// Validate status 2xx",
- "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
- "});",
- "",
- "// Validate if response header has matching content-type",
- "pm.test(\"[GET]::/payments/:id - 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(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
- " pm.response.to.have.jsonBody();",
- "});",
- "",
- "// Set response object as internal variable",
- "let jsonData = {};",
- "try {",
- " jsonData = pm.response.json();",
- "} catch (e) {}",
- "",
- "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
- "if (jsonData?.payment_id) {",
- " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
- " console.log(",
- " \"- use {{payment_id}} as collection variable for value\",",
- " jsonData.payment_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
- " );",
- "}",
- "",
- "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
- "if (jsonData?.mandate_id) {",
- " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
- " console.log(",
- " \"- use {{mandate_id}} as collection variable for value\",",
- " jsonData.mandate_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
- " );",
- "}",
- "",
- "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
- "if (jsonData?.client_secret) {",
- " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
- " console.log(",
- " \"- use {{client_secret}} as collection variable for value\",",
- " jsonData.client_secret,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
- " );",
- "}",
- "",
- "// Response body should have value \"Succeeded\" for \"status\"",
- "if (jsonData?.status) {",
- " pm.test(",
- " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",",
- " function () {",
- " pm.expect(jsonData.status).to.eql(\"succeeded\");",
- " },",
- " );",
- "}",
- "",
- "// Response body should have \"mandate_id\"",
- "pm.test(",
- " \"[POST]::/payments - Content check if 'mandate_id' exists\",",
- " function () {",
- " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;",
- " },",
- ");",
- "",
- "// Response body should have \"mandate_data\"",
- "pm.test(",
- " \"[POST]::/payments - Content check if 'mandate_data' exists\",",
- " function () {",
- " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;",
- " },",
- ");",
- ""
- ],
- "type": "text/javascript"
- }
- }
- ],
- "request": {
- "method": "GET",
- "header": [
- {
- "key": "Accept",
- "value": "application/json"
- }
- ],
- "url": {
- "raw": "{{baseUrl}}/payments/:id?force_sync=true",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments",
- ":id"
- ],
- "query": [
- {
- "key": "force_sync",
- "value": "true"
- }
- ],
- "variable": [
- {
- "key": "id",
- "value": "{{payment_id}}",
- "description": "(Required) unique payment id"
- }
- ]
- },
- "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
- },
- "response": []
- }
- ]
- },
- {
- "name": "Scenario11-Refund recurring payment",
- "item": [
- {
- "name": "Payments - Create",
- "event": [
- {
- "listen": "prerequest",
- "script": {
- "exec": [
- "pm.environment.set(\"random_number\", _.random(100, 100000));",
- ""
- ],
- "type": "text/javascript"
- }
- },
- {
- "listen": "test",
- "script": {
- "exec": [
- "// Set the environment variable 'amount' with the value from the response",
- "pm.environment.set(\"amount\", pm.response.json().amount);",
- "",
- "// Validate status 2xx",
- "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
- "});",
- "",
- "// Validate if response header has matching content-type",
- "pm.test(\"[POST]::/payments - 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]::/payments - Response has JSON Body\", function () {",
- " pm.response.to.have.jsonBody();",
- "});",
- "",
- "// Set response object as internal variable",
- "let jsonData = {};",
- "try {",
- " jsonData = pm.response.json();",
- "} catch (e) {}",
- "",
- "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
- "if (jsonData?.payment_id) {",
- " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
- " console.log(",
- " \"- use {{payment_id}} as collection variable for value\",",
- " jsonData.payment_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
- " );",
- "}",
- "",
- "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
- "if (jsonData?.mandate_id) {",
- " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
- " console.log(",
- " \"- use {{mandate_id}} as collection variable for value\",",
- " jsonData.mandate_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
- " );",
- "}",
- "",
- "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
- "if (jsonData?.client_secret) {",
- " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
- " console.log(",
- " \"- use {{client_secret}} as collection variable for value\",",
- " jsonData.client_secret,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
- " );",
- "}",
- "",
- "// Response body should have value \"processing\" for \"status\"",
- "if (jsonData?.status) {",
- " pm.test(",
- " \"[POST]::/payments - Content check if value for 'status' matches 'processing'\",",
- " function () {",
- " pm.expect(jsonData.status).to.eql(\"processing\");",
- " },",
- " );",
- "}",
- "",
- "// Response body should have \"mandate_id\"",
- "pm.test(",
- " \"[POST]::/payments - Content check if 'mandate_id' exists\",",
- " function () {",
- " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;",
- " },",
- ");",
- "",
- "// Response body should have \"mandate_data\"",
- "pm.test(",
- " \"[POST]::/payments - Content check if 'mandate_data' exists\",",
- " function () {",
- " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;",
- " },",
- ");",
- ""
- ],
- "type": "text/javascript"
- }
- }
- ],
- "request": {
- "method": "POST",
- "header": [
- {
- "key": "Content-Type",
- "value": "application/json"
- },
- {
- "key": "Accept",
- "value": "application/json"
- }
- ],
- "body": {
- "mode": "raw",
- "options": {
- "raw": {
- "language": "json"
- }
- },
- "raw": "{\"amount\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"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://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4111111111111111\",\"card_exp_month\":\"10\",\"card_exp_year\":\"69\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"setup_future_usage\":\"off_session\",\"mandate_data\":{\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"127.0.0.1\",\"user_agent\":\"amet irure esse\"}},\"mandate_type\":{\"single_use\":{\"amount\":100000,\"currency\":\"USD\"}}},\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"127.0.0.1\",\"user_agent\":\"amet irure esse\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
- },
- "url": {
- "raw": "{{baseUrl}}/payments",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments"
- ]
- },
- "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
- },
- "response": []
- },
- {
- "name": "Payments - Retrieve",
- "event": [
- {
- "listen": "test",
- "script": {
- "exec": [
- "// Validate status 2xx",
- "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
- "});",
- "",
- "// Validate if response header has matching content-type",
- "pm.test(\"[GET]::/payments/:id - 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(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
- " pm.response.to.have.jsonBody();",
- "});",
- "",
- "// Set response object as internal variable",
- "let jsonData = {};",
- "try {",
- " jsonData = pm.response.json();",
- "} catch (e) {}",
- "",
- "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
- "if (jsonData?.payment_id) {",
- " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
- " console.log(",
- " \"- use {{payment_id}} as collection variable for value\",",
- " jsonData.payment_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
- " );",
- "}",
- "",
- "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
- "if (jsonData?.mandate_id) {",
- " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
- " console.log(",
- " \"- use {{mandate_id}} as collection variable for value\",",
- " jsonData.mandate_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
- " );",
- "}",
- "",
- "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
- "if (jsonData?.client_secret) {",
- " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
- " console.log(",
- " \"- use {{client_secret}} as collection variable for value\",",
- " jsonData.client_secret,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
- " );",
- "}",
- "",
- "// Response body should have value \"Succeeded\" for \"status\"",
- "if (jsonData?.status) {",
- " pm.test(",
- " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",",
- " function () {",
- " pm.expect(jsonData.status).to.eql(\"succeeded\");",
- " },",
- " );",
- "}",
- "",
- "// Response body should have \"mandate_id\"",
- "pm.test(",
- " \"[POST]::/payments - Content check if 'mandate_id' exists\",",
- " function () {",
- " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;",
- " },",
- ");",
- "",
- "// Response body should have \"mandate_data\"",
- "pm.test(",
- " \"[POST]::/payments - Content check if 'mandate_data' exists\",",
- " function () {",
- " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;",
- " },",
- ");",
- ""
- ],
- "type": "text/javascript"
- }
- }
- ],
- "request": {
- "method": "GET",
- "header": [
- {
- "key": "Accept",
- "value": "application/json"
- }
- ],
- "url": {
- "raw": "{{baseUrl}}/payments/:id?force_sync=true",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments",
- ":id"
- ],
- "query": [
- {
- "key": "force_sync",
- "value": "true"
- }
- ],
- "variable": [
- {
- "key": "id",
- "value": "{{payment_id}}",
- "description": "(Required) unique payment id"
- }
- ]
- },
- "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
- },
- "response": []
- },
- {
- "name": "Recurring Payments - Create",
- "event": [
- {
- "listen": "prerequest",
- "script": {
- "exec": [
- "pm.environment.set(\"random_number\", _.random(100, 100000));",
- ""
- ],
- "type": "text/javascript"
- }
- },
- {
- "listen": "test",
- "script": {
- "exec": [
- "// Set the environment variable 'amount' with the value from the response",
- "pm.environment.set(\"amount\", pm.response.json().amount);",
- "",
- "// Validate status 2xx",
- "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
- "});",
- "",
- "// Validate if response header has matching content-type",
- "pm.test(\"[POST]::/payments - 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]::/payments - Response has JSON Body\", function () {",
- " pm.response.to.have.jsonBody();",
- "});",
- "",
- "// Set response object as internal variable",
- "let jsonData = {};",
- "try {",
- " jsonData = pm.response.json();",
- "} catch (e) {}",
- "",
- "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
- "if (jsonData?.payment_id) {",
- " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
- " console.log(",
- " \"- use {{payment_id}} as collection variable for value\",",
- " jsonData.payment_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
- " );",
- "}",
- "",
- "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
- "if (jsonData?.mandate_id) {",
- " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
- " console.log(",
- " \"- use {{mandate_id}} as collection variable for value\",",
- " jsonData.mandate_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
- " );",
- "}",
- "",
- "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
- "if (jsonData?.client_secret) {",
- " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
- " console.log(",
- " \"- use {{client_secret}} as collection variable for value\",",
- " jsonData.client_secret,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
- " );",
- "}",
- "",
- "// Response body should have value \"processing\" for \"status\"",
- "if (jsonData?.status) {",
- " pm.test(",
- " \"[POST]::/payments - Content check if value for 'status' matches 'processing'\",",
- " function () {",
- " pm.expect(jsonData.status).to.eql(\"processing\");",
- " },",
- " );",
- "}",
- "",
- "// Response body should have \"mandate_id\"",
- "pm.test(",
- " \"[POST]::/payments - Content check if 'mandate_id' exists\",",
- " function () {",
- " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;",
- " },",
- ");",
- "",
- "// Response body should have \"mandate_data\"",
- "pm.test(",
- " \"[POST]::/payments - Content check if 'mandate_data' exists\",",
- " function () {",
- " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;",
- " },",
- ");",
- "",
- "// Response body should have \"payment_method_data\"",
- "pm.test(",
- " \"[POST]::/payments - Content check if 'payment_method_data' exists\",",
- " function () {",
- " pm.expect(typeof jsonData.payment_method_data !== \"undefined\").to.be.true;",
- " },",
- ");",
- ""
- ],
- "type": "text/javascript"
- }
- }
- ],
- "request": {
- "method": "POST",
- "header": [
- {
- "key": "Content-Type",
- "value": "application/json"
- },
- {
- "key": "Accept",
- "value": "application/json"
- }
- ],
- "body": {
- "mode": "raw",
- "options": {
- "raw": {
- "language": "json"
- }
- },
- "raw": "{\"amount\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"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://duck.com\",\"mandate_id\":\"{{mandate_id}}\",\"off_session\":true,\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
- },
- "url": {
- "raw": "{{baseUrl}}/payments",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments"
- ]
- },
- "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
- },
- "response": []
- },
- {
- "name": "Payments - Retrieve-copy",
- "event": [
- {
- "listen": "test",
- "script": {
- "exec": [
- "// Validate status 2xx",
- "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
- "});",
- "",
- "// Validate if response header has matching content-type",
- "pm.test(\"[GET]::/payments/:id - 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(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
- " pm.response.to.have.jsonBody();",
- "});",
- "",
- "// Set response object as internal variable",
- "let jsonData = {};",
- "try {",
- " jsonData = pm.response.json();",
- "} catch (e) {}",
- "",
- "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
- "if (jsonData?.payment_id) {",
- " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
- " console.log(",
- " \"- use {{payment_id}} as collection variable for value\",",
- " jsonData.payment_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
- " );",
- "}",
- "",
- "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
- "if (jsonData?.mandate_id) {",
- " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
- " console.log(",
- " \"- use {{mandate_id}} as collection variable for value\",",
- " jsonData.mandate_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
- " );",
- "}",
- "",
- "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
- "if (jsonData?.client_secret) {",
- " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
- " console.log(",
- " \"- use {{client_secret}} as collection variable for value\",",
- " jsonData.client_secret,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
- " );",
- "}",
- "",
- "// Response body should have value \"Succeeded\" for \"status\"",
- "if (jsonData?.status) {",
- " pm.test(",
- " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",",
- " function () {",
- " pm.expect(jsonData.status).to.eql(\"succeeded\");",
- " },",
- " );",
- "}",
- "",
- "// Response body should have \"mandate_id\"",
- "pm.test(",
- " \"[POST]::/payments - Content check if 'mandate_id' exists\",",
- " function () {",
- " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;",
- " },",
- ");",
- "",
- "// Response body should have \"mandate_data\"",
- "pm.test(",
- " \"[POST]::/payments - Content check if 'mandate_data' exists\",",
- " function () {",
- " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;",
- " },",
- ");",
- ""
- ],
- "type": "text/javascript"
- }
- }
- ],
- "request": {
- "method": "GET",
- "header": [
- {
- "key": "Accept",
- "value": "application/json"
- }
- ],
- "url": {
- "raw": "{{baseUrl}}/payments/:id?force_sync=true",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments",
- ":id"
- ],
- "query": [
- {
- "key": "force_sync",
- "value": "true"
- }
- ],
- "variable": [
- {
- "key": "id",
- "value": "{{payment_id}}",
- "description": "(Required) unique payment id"
- }
- ]
- },
- "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
- },
- "response": []
- },
- {
- "name": "Refunds - Create",
- "event": [
- {
- "listen": "prerequest",
- "script": {
- "exec": [
- ""
- ],
- "type": "text/javascript"
- }
- },
- {
- "listen": "test",
- "script": {
- "exec": [
- "// Get the value of 'amount' from the environment",
- "const amount = pm.environment.get(\"amount\");",
- "",
- "// Validate status 2xx",
- "pm.test(\"[POST]::/refunds - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
- "});",
- "",
- "// Validate if response header has matching content-type",
- "pm.test(\"[POST]::/refunds - Content-Type is application/json\", function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
- " \"application/json\",",
- " );",
- "});",
- "",
- "// Set response object as internal variable",
- "let jsonData = {};",
- "try {",
- " jsonData = pm.response.json();",
- "} catch (e) {}",
- "",
- "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id",
- "if (jsonData?.refund_id) {",
- " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);",
- " console.log(",
- " \"- use {{refund_id}} as collection variable for value\",",
- " jsonData.refund_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",",
- " );",
- "}",
- "",
- "// Response body should have value \"pending\" for \"status\"",
- "if (jsonData?.status) {",
- " pm.test(",
- " \"[POST]::/refunds - Content check if value for 'status' matches 'pending'\",",
- " function () {",
- " pm.expect(jsonData.status).to.eql(\"pending\");",
- " },",
- " );",
- "}",
- "",
- "// Response body should have value for \"amount\"",
- "if (jsonData?.status) {",
- " pm.test(",
- " \"[POST]::/refunds - Content check if value for 'amount' matches '{{amount}}'\",",
- " function () {",
- " pm.expect(jsonData.amount).to.eql(amount);",
- " },",
- " );",
- "}",
- ""
- ],
- "type": "text/javascript"
- }
- }
- ],
- "request": {
- "method": "POST",
- "header": [
- {
- "key": "Content-Type",
- "value": "application/json"
- },
- {
- "key": "Accept",
- "value": "application/json"
- }
- ],
- "body": {
- "mode": "raw",
- "options": {
- "raw": {
- "language": "json"
- }
- },
- "raw": "{\"payment_id\":\"{{payment_id}}\",\"amount\":\"{{amount}}\",\"reason\":\"Customer returned product\",\"refund_type\":\"instant\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
- },
- "url": {
- "raw": "{{baseUrl}}/refunds",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "refunds"
- ]
- },
- "description": "To create a refund against an already processed payment"
- },
- "response": []
- },
- {
- "name": "Refunds - Retrieve",
- "event": [
- {
- "listen": "prerequest",
- "script": {
- "exec": [
- ""
- ],
- "type": "text/javascript"
- }
- },
- {
- "listen": "test",
- "script": {
- "exec": [
- "// Get the value of 'amount' from the environment",
- "const refund_amount = pm.environment.get(\"amount\");",
- "",
- "// Validate status 2xx",
- "pm.test(\"[GET]::/refunds/:id - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
- "});",
- "",
- "// Validate if response header has matching content-type",
- "pm.test(\"[GET]::/refunds/:id - Content-Type is application/json\", function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
- " \"application/json\",",
- " );",
- "});",
- "",
- "// Set response object as internal variable",
- "let jsonData = {};",
- "try {",
- " jsonData = pm.response.json();",
- "} catch (e) {}",
- "",
- "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id",
- "if (jsonData?.refund_id) {",
- " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);",
- " console.log(",
- " \"- use {{refund_id}} as collection variable for value\",",
- " jsonData.refund_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",",
- " );",
- "}",
- "",
- "// Response body should have value \"succeeded\" for \"status\"",
- "if (jsonData?.status) {",
- " pm.test(",
- " \"[POST]::/refunds - Content check if value for 'status' matches 'succeeded'\",",
- " function () {",
- " pm.expect(jsonData.status).to.eql(\"succeeded\");",
- " },",
- " );",
- "}",
- "",
- "// Response body should have value for \"refund_amount\"",
- "if (jsonData?.status) {",
- " pm.test(",
- " \"[POST]::/refunds - Content check if value for 'refund_amount' matches '{{refund_amount}}'\",",
- " function () {",
- " pm.expect(jsonData.amount).to.eql(refund_amount);",
- " },",
- " );",
- "}",
- ""
- ],
- "type": "text/javascript"
- }
- }
- ],
- "request": {
- "method": "GET",
- "header": [
- {
- "key": "Accept",
- "value": "application/json"
- }
- ],
- "url": {
- "raw": "{{baseUrl}}/refunds/:id",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "refunds",
- ":id"
- ],
- "variable": [
- {
- "key": "id",
- "value": "{{refund_id}}",
- "description": "(Required) unique refund id"
- }
- ]
- },
- "description": "To retrieve the properties of a Refund. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
- },
- "response": []
- }
- ]
- },
- {
- "name": "Scenario12-Add card flow",
+ "name": "Scenario10-Add card flow",
"item": [
{
"name": "Payments - Create",
@@ -8465,7 +7104,7 @@
]
},
{
- "name": "Scenario13-Don't Pass CVV for save card flow and verify success payment",
+ "name": "Scenario11-Don't Pass CVV for save card flow and verify success payment",
"item": [
{
"name": "Payments - Create",
@@ -8970,7 +7609,7 @@
]
},
{
- "name": "Scenario14-Save card payment with manual capture",
+ "name": "Scenario12-Save card payment with manual capture",
"item": [
{
"name": "Payments - Create",
@@ -10338,7 +8977,7 @@
]
},
{
- "name": "Scenario15-Create payment without customer_id and with billing address and shipping address",
+ "name": "Scenario13-Create payment without customer_id and with billing address and shipping address",
"item": [
{
"name": "Payments - Create",
diff --git a/postman/collection-json/paypal.postman_collection.json b/postman/collection-json/paypal.postman_collection.json
index 4270035992f..bcb508da4c0 100644
--- a/postman/collection-json/paypal.postman_collection.json
+++ b/postman/collection-json/paypal.postman_collection.json
@@ -5402,7 +5402,7 @@
"let jsonData = {};",
"try {",
" jsonData = pm.response.json();",
- "} catch (e) {}",
+ "} catch (e) { }",
"",
"// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
"if (jsonData?.payment_id) {",
@@ -5456,9 +5456,9 @@
"// Response body should have value \"requires_confirmation\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments - Content check if value for 'error_code' matches 'UNPROCESSABLE_ENTITY'\",",
+ " \"[POST]::/payments - Content check if value for 'error_code' matches 'VALIDATION_ERROR'\",",
" function () {",
- " pm.expect(jsonData.error_code).to.eql(\"UNPROCESSABLE_ENTITY\");",
+ " pm.expect(jsonData.error_code).to.eql(\"VALIDATION_ERROR\");",
" },",
" );",
"}",
|
2024-03-19T11:03:12Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [x] CI/CD
## Description
<!-- Describe your changes in detail -->
touched 2 collections namely, NMI and PayPal:
- fixed assertion in PayPal which broke due to [this](https://github.com/juspay/hyperswitch/commit/fc81f90f6168dc6e08cbfacdda0f59e99def07da) commit
- removed mandate collection from NMI as it is not supported
closes #4127
### 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).
-->
Reduce reds.
## 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)?
-->
- NMI
<img width="486" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/53f628e9-693f-4794-8ed9-64f53afb82be">
- PayPal
<img width="499" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/b6c4f789-1b85-4dbf-bb6d-1dcafc6420b0">
`.json` files are auto-generate from `dir`
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
944089d6914cb6bece9056f78b9aabf90e485151
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4097
|
Bug: Accepting PM ID as PM data in /payments
This is to add support for accepting an existing and active PM ID as `payment_method_data` in `/payments` request.
|
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 51b95041898..c3ab9e00c6d 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -52,7 +52,9 @@ use crate::{
self,
types::{self, AsyncLift},
},
- storage::{self, enums as storage_enums, ephemeral_key, CustomerUpdate::Update},
+ storage::{
+ self, enums as storage_enums, ephemeral_key, CardTokenData, CustomerUpdate::Update,
+ },
transformers::{ForeignFrom, ForeignTryFrom},
ErrorResponse, MandateReference, RouterData,
},
@@ -1848,6 +1850,25 @@ pub async fn make_pm_data<'a, F: Clone, R, Ctx: PaymentMethodRetrieve>(
}
}
+ if payment_data.token_data.is_none() {
+ if let Some(payment_method_info) = &payment_data.payment_method_info {
+ if payment_method_info.payment_method == storage_enums::PaymentMethod::Card {
+ payment_data.token_data =
+ Some(storage::PaymentTokenData::PermanentCard(CardTokenData {
+ payment_method_id: Some(payment_method_info.payment_method_id.clone()),
+ locker_id: payment_method_info
+ .locker_id
+ .clone()
+ .or(Some(payment_method_info.payment_method_id.clone())),
+ token: payment_method_info
+ .locker_id
+ .clone()
+ .unwrap_or(payment_method_info.payment_method_id.clone()),
+ }));
+ }
+ }
+ }
+
// TODO: Handle case where payment method and token both are present in request properly.
let (payment_method, pm_id) = match (request, payment_data.token_data.as_ref()) {
(_, Some(hyperswitch_token)) => {
|
2024-04-08T12:58: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 is to add support for accepting an existing and active PM ID as payment_method_data 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) Create MCA
2) Copy the profile and hit the below curl to enable pg_agnostic config
```
curl --location 'https://sandbox.hyperswitch.io/routing/business_profile/:business_profile_id/configs/pg_agnostic_mit' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'Authorization: Bearer JWT_Token' \
--data '{
"enabled": true
}'
```
<img width="939" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/2853f047-97c3-4f44-9f25-a642a49b60a4">
3) Do setup mandate for the pm_id
```
{
"amount": 100,
"currency": "USD",
"confirm": true,
"profile_id": "pro_RsqZK1Xdmtd9KbAK8YNs",
"capture_method": "automatic",
"customer_id": "mandate_customer1",
"email": "guest@example.com",
"setup_future_usage": "off_session",
"customer_acceptance": {
"acceptance_type": "online"
},
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": "Test Holder",
"card_cvc": "737"
}
},
"payment_type": "setup_mandate",
"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"
}
```
<img width="1106" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/20f73b3f-a390-4bb6-a4b0-e7dec320ebf4">
4) Copy the `payment_method_id` from the above response and use it to do a mit
```
{
"amount": 499,
"currency": "USD",
"confirm": true,
"profile_id": "pro_RsqZK1Xdmtd9KbAK8YNs",
"capture_method": "automatic",
"customer_id": "mandate_customer1",
"email": "guest@example.com",
"off_session": true,
"recurring_details": {
"type": "payment_method_id",
"data": "pm_1f5oJ8YVuHkWsxr9nA8t"
},
"payment_method": "card",
"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"
}
}
```
<img width="1129" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/94fac52a-52aa-4136-a0fd-e344dd701380">
## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
e0e843715cd02ac8b2eff2f645fe8471551ee914
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4099
|
Bug: Generate Client Secret for /payment_methods requests
Create a `PM Client Secret` during the `/payment_methods` API request.
This would to be stored in the PM Table and used as reference for updating the PM record once the card is saved.
|
diff --git a/crates/api_models/src/events/payment.rs b/crates/api_models/src/events/payment.rs
index b27ca142c94..b8f4a9d6d90 100644
--- a/crates/api_models/src/events/payment.rs
+++ b/crates/api_models/src/events/payment.rs
@@ -90,7 +90,7 @@ impl ApiEventMetric for PaymentMethodResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::PaymentMethod {
payment_method_id: self.payment_method_id.clone(),
- payment_method: Some(self.payment_method),
+ payment_method: self.payment_method,
payment_method_type: self.payment_method_type,
})
}
diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs
index 7eb7e213e5b..e9ff261a632 100644
--- a/crates/api_models/src/payment_methods.rs
+++ b/crates/api_models/src/payment_methods.rs
@@ -22,7 +22,7 @@ use crate::{
pub struct PaymentMethodCreate {
/// The type of payment method use for the payment.
#[schema(value_type = PaymentMethod,example = "card")]
- pub payment_method: api_enums::PaymentMethod,
+ pub payment_method: Option<api_enums::PaymentMethod>,
/// This is a sub-category of payment method.
#[schema(value_type = Option<PaymentMethodType>,example = "credit")]
@@ -65,6 +65,16 @@ pub struct PaymentMethodCreate {
#[cfg(feature = "payouts")]
#[schema(value_type = Option<Wallet>)]
pub wallet: Option<payouts::Wallet>,
+
+ /// For Client based calls, SDK will use the client_secret
+ /// in order to call /payment_methods
+ /// Client secret will be generated whenever a new
+ /// payment method is created
+ pub client_secret: Option<String>,
+
+ /// Payment method data to be passed in case of client
+ /// based flow
+ pub payment_method_data: Option<PaymentMethodCreateData>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
@@ -101,6 +111,15 @@ pub struct PaymentMethodUpdate {
pub client_secret: Option<String>,
}
+#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
+#[serde(deny_unknown_fields)]
+#[serde(rename_all = "snake_case")]
+#[serde(rename = "payment_method_data")]
+
+pub enum PaymentMethodCreateData {
+ Card(CardDetail),
+}
+
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct CardDetail {
@@ -202,7 +221,7 @@ pub struct PaymentMethodResponse {
/// The type of payment method use for the payment.
#[schema(value_type = PaymentMethod, example = "card")]
- pub payment_method: api_enums::PaymentMethod,
+ pub payment_method: Option<api_enums::PaymentMethod>,
/// This is a sub-category of payment method.
#[schema(value_type = Option<PaymentMethodType>, example = "credit")]
@@ -242,6 +261,9 @@ pub struct PaymentMethodResponse {
#[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>,
+
+ /// For Client based calls
+ pub client_secret: Option<String>,
}
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index 9dbe5f4f4bc..a5caac3fb35 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -1252,6 +1252,8 @@ pub enum PaymentMethodStatus {
/// Indicates that the payment method is awaiting some data or action before it can be marked
/// as 'active'.
Processing,
+ /// Indicates that the payment method is awaiting some data before changing state to active
+ AwaitingData,
}
impl From<AttemptStatus> for PaymentMethodStatus {
diff --git a/crates/diesel_models/src/payment_method.rs b/crates/diesel_models/src/payment_method.rs
index dbdbc78aa05..e2807f3b5ea 100644
--- a/crates/diesel_models/src/payment_method.rs
+++ b/crates/diesel_models/src/payment_method.rs
@@ -27,7 +27,7 @@ pub struct PaymentMethod {
pub direct_debit_token: Option<String>,
pub created_at: PrimitiveDateTime,
pub last_modified: PrimitiveDateTime,
- pub payment_method: storage_enums::PaymentMethod,
+ pub payment_method: Option<storage_enums::PaymentMethod>,
pub payment_method_type: Option<storage_enums::PaymentMethodType>,
pub payment_method_issuer: Option<String>,
pub payment_method_issuer_code: Option<storage_enums::PaymentMethodIssuerCode>,
@@ -39,6 +39,7 @@ pub struct PaymentMethod {
pub customer_acceptance: Option<pii::SecretSerdeValue>,
pub status: storage_enums::PaymentMethodStatus,
pub network_transaction_id: Option<String>,
+ pub client_secret: Option<String>,
}
#[derive(
@@ -49,7 +50,7 @@ pub struct PaymentMethodNew {
pub customer_id: String,
pub merchant_id: String,
pub payment_method_id: String,
- pub payment_method: storage_enums::PaymentMethod,
+ pub payment_method: Option<storage_enums::PaymentMethod>,
pub payment_method_type: Option<storage_enums::PaymentMethodType>,
pub payment_method_issuer: Option<String>,
pub payment_method_issuer_code: Option<storage_enums::PaymentMethodIssuerCode>,
@@ -73,6 +74,7 @@ pub struct PaymentMethodNew {
pub customer_acceptance: Option<pii::SecretSerdeValue>,
pub status: storage_enums::PaymentMethodStatus,
pub network_transaction_id: Option<String>,
+ pub client_secret: Option<String>,
}
impl Default for PaymentMethodNew {
@@ -84,7 +86,7 @@ impl Default for PaymentMethodNew {
merchant_id: String::default(),
payment_method_id: String::default(),
locker_id: Option::default(),
- payment_method: storage_enums::PaymentMethod::default(),
+ payment_method: Option::default(),
payment_method_type: Option::default(),
payment_method_issuer: Option::default(),
payment_method_issuer_code: Option::default(),
@@ -107,6 +109,7 @@ impl Default for PaymentMethodNew {
customer_acceptance: Option::default(),
status: storage_enums::PaymentMethodStatus::Active,
network_transaction_id: Option::default(),
+ client_secret: Option::default(),
}
}
}
@@ -135,6 +138,12 @@ pub enum PaymentMethodUpdate {
StatusUpdate {
status: Option<storage_enums::PaymentMethodStatus>,
},
+ AdditionalDataUpdate {
+ payment_method_data: Option<Encryption>,
+ status: Option<storage_enums::PaymentMethodStatus>,
+ locker_id: Option<String>,
+ payment_method: Option<storage_enums::PaymentMethod>,
+ },
ConnectorMandateDetailsUpdate {
connector_mandate_details: Option<serde_json::Value>,
},
@@ -150,6 +159,8 @@ pub struct PaymentMethodUpdateInternal {
last_used_at: Option<PrimitiveDateTime>,
network_transaction_id: Option<String>,
status: Option<storage_enums::PaymentMethodStatus>,
+ locker_id: Option<String>,
+ payment_method: Option<storage_enums::PaymentMethod>,
connector_mandate_details: Option<serde_json::Value>,
}
@@ -168,6 +179,7 @@ impl PaymentMethodUpdateInternal {
network_transaction_id,
status,
connector_mandate_details,
+ ..
} = self;
PaymentMethod {
@@ -193,6 +205,8 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
last_used_at: None,
network_transaction_id: None,
status: None,
+ locker_id: None,
+ payment_method: None,
connector_mandate_details: None,
},
PaymentMethodUpdate::PaymentMethodDataUpdate {
@@ -203,6 +217,8 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
last_used_at: None,
network_transaction_id: None,
status: None,
+ locker_id: None,
+ payment_method: None,
connector_mandate_details: None,
},
PaymentMethodUpdate::LastUsedUpdate { last_used_at } => Self {
@@ -211,6 +227,8 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
last_used_at: Some(last_used_at),
network_transaction_id: None,
status: None,
+ locker_id: None,
+ payment_method: None,
connector_mandate_details: None,
},
PaymentMethodUpdate::NetworkTransactionIdAndStatusUpdate {
@@ -222,6 +240,8 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
last_used_at: None,
network_transaction_id,
status,
+ locker_id: None,
+ payment_method: None,
connector_mandate_details: None,
},
PaymentMethodUpdate::StatusUpdate { status } => Self {
@@ -230,6 +250,23 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
last_used_at: None,
network_transaction_id: None,
status,
+ locker_id: None,
+ payment_method: None,
+ connector_mandate_details: None,
+ },
+ PaymentMethodUpdate::AdditionalDataUpdate {
+ payment_method_data,
+ status,
+ locker_id,
+ payment_method,
+ } => Self {
+ metadata: None,
+ payment_method_data,
+ last_used_at: None,
+ network_transaction_id: None,
+ status,
+ locker_id,
+ payment_method,
connector_mandate_details: None,
},
PaymentMethodUpdate::ConnectorMandateDetailsUpdate {
@@ -239,6 +276,8 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
payment_method_data: None,
last_used_at: None,
status: None,
+ locker_id: None,
+ payment_method: None,
connector_mandate_details,
network_transaction_id: None,
},
@@ -277,6 +316,7 @@ impl From<&PaymentMethodNew> for PaymentMethod {
customer_acceptance: payment_method_new.customer_acceptance.clone(),
status: payment_method_new.status,
network_transaction_id: payment_method_new.network_transaction_id.clone(),
+ client_secret: payment_method_new.client_secret.clone(),
}
}
}
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index f4255bfd737..bbe8a8060fc 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -904,7 +904,7 @@ diesel::table! {
direct_debit_token -> Nullable<Varchar>,
created_at -> Timestamp,
last_modified -> Timestamp,
- payment_method -> Varchar,
+ payment_method -> Nullable<Varchar>,
#[max_length = 64]
payment_method_type -> Nullable<Varchar>,
#[max_length = 128]
@@ -921,6 +921,8 @@ diesel::table! {
status -> Varchar,
#[max_length = 255]
network_transaction_id -> Nullable<Varchar>,
+ #[max_length = 128]
+ client_secret -> Nullable<Varchar>,
}
}
diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs
index 972dde7542a..6e9ad5848c5 100644
--- a/crates/openapi/src/openapi.rs
+++ b/crates/openapi/src/openapi.rs
@@ -206,6 +206,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payment_methods::PaymentMethodUpdate,
api_models::payment_methods::CustomerDefaultPaymentMethodResponse,
api_models::payment_methods::CardDetailFromLocker,
+ api_models::payment_methods::PaymentMethodCreateData,
api_models::payment_methods::CardDetail,
api_models::payment_methods::CardDetailUpdate,
api_models::payment_methods::RequestPaymentMethodTypes,
diff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rs
index c38167f07c4..af97c500f3e 100644
--- a/crates/router/src/core/customers.rs
+++ b/crates/router/src/core/customers.rs
@@ -223,9 +223,10 @@ pub async fn delete_customer(
)
.await
{
+ // check this in review
Ok(customer_payment_methods) => {
for pm in customer_payment_methods.into_iter() {
- if pm.payment_method == enums::PaymentMethod::Card {
+ if pm.payment_method == Some(enums::PaymentMethod::Card) {
cards::delete_card_from_locker(
&state,
&req.customer_id,
diff --git a/crates/router/src/core/locker_migration.rs b/crates/router/src/core/locker_migration.rs
index 53f503e8711..bad3b2184b5 100644
--- a/crates/router/src/core/locker_migration.rs
+++ b/crates/router/src/core/locker_migration.rs
@@ -85,7 +85,7 @@ pub async fn call_to_locker(
for pm in payment_methods
.into_iter()
- .filter(|pm| matches!(pm.payment_method, storage_enums::PaymentMethod::Card))
+ .filter(|pm| matches!(pm.payment_method, Some(storage_enums::PaymentMethod::Card)))
{
let card = cards::get_card_from_locker(
state,
@@ -128,6 +128,8 @@ pub async fn call_to_locker(
metadata: pm.metadata,
customer_id: Some(pm.customer_id),
card_network: card.card_brand,
+ client_secret: None,
+ payment_method_data: None,
};
let add_card_result = cards::add_card_hs(
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index c14042c9e62..25bb869075c 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -85,6 +85,7 @@ pub async fn create_payment_method(
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,
) -> errors::CustomResult<storage::PaymentMethod, errors::ApiErrorResponse> {
@@ -98,6 +99,11 @@ pub async fn create_payment_method(
.await
.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;
+ let client_secret = generate_id(
+ consts::ID_LENGTH,
+ format!("{payment_method_id}_secret").as_str(),
+ );
+
let response = db
.insert_payment_method(
storage::PaymentMethodNew {
@@ -113,6 +119,8 @@ pub async fn create_payment_method(
payment_method_data,
connector_mandate_details,
customer_acceptance: customer_acceptance.map(masking::Secret::new),
+ client_secret: Some(client_secret),
+ status: status.unwrap_or(enums::PaymentMethodStatus::Active),
network_transaction_id: network_transaction_id.to_owned(),
..storage::PaymentMethodNew::default()
},
@@ -122,7 +130,7 @@ pub async fn create_payment_method(
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to add payment method in db")?;
- if customer.default_payment_method_id.is_none() {
+ if customer.default_payment_method_id.is_none() && req.payment_method.is_some() {
let _ = set_default_payment_method(
db,
merchant_id.to_string(),
@@ -161,6 +169,7 @@ pub fn store_default_payment_method(
installment_payment_enabled: false, //[#219]
payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]),
last_used_at: Some(common_utils::date_time::now()),
+ client_secret: None,
};
(payment_method_response, None)
@@ -233,6 +242,253 @@ pub async fn get_or_insert_payment_method(
}
}
+#[instrument(skip_all)]
+pub async fn get_client_secret_or_add_payment_method(
+ state: routes::AppState,
+ req: api::PaymentMethodCreate,
+ merchant_account: &domain::MerchantAccount,
+ key_store: &domain::MerchantKeyStore,
+) -> errors::RouterResponse<api::PaymentMethodResponse> {
+ let db = &*state.store;
+ let merchant_id = &merchant_account.merchant_id;
+ let customer_id = req.customer_id.clone().get_required_value("customer_id")?;
+
+ #[cfg(not(feature = "payouts"))]
+ let condition = req.card.is_some();
+ #[cfg(feature = "payouts")]
+ let condition = req.card.is_some() || req.bank_transfer.is_some() || req.wallet.is_some();
+
+ if condition {
+ add_payment_method(state, req, merchant_account, key_store).await
+ } else {
+ let payment_method_id = generate_id(consts::ID_LENGTH, "pm");
+
+ let res = create_payment_method(
+ db,
+ &req,
+ customer_id.as_str(),
+ payment_method_id.as_str(),
+ None,
+ merchant_id.as_str(),
+ None,
+ None,
+ None,
+ key_store,
+ None,
+ Some(enums::PaymentMethodStatus::AwaitingData),
+ None,
+ merchant_account.storage_scheme,
+ )
+ .await?;
+
+ Ok(services::api::ApplicationResponse::Json(
+ api::PaymentMethodResponse::foreign_from(res),
+ ))
+ }
+}
+
+#[instrument(skip_all)]
+pub fn authenticate_pm_client_secret_and_check_expiry(
+ req_client_secret: &String,
+ payment_method: &diesel_models::PaymentMethod,
+) -> errors::CustomResult<bool, errors::ApiErrorResponse> {
+ let stored_client_secret = payment_method
+ .client_secret
+ .clone()
+ .get_required_value("client_secret")
+ .change_context(errors::ApiErrorResponse::MissingRequiredField {
+ field_name: "client_secret",
+ })
+ .attach_printable("client secret not found in db")?;
+
+ if req_client_secret != &stored_client_secret {
+ Err((errors::ApiErrorResponse::ClientSecretInvalid).into())
+ } else {
+ let current_timestamp = common_utils::date_time::now();
+ let session_expiry = payment_method
+ .created_at
+ .saturating_add(time::Duration::seconds(consts::DEFAULT_SESSION_EXPIRY));
+
+ let expired = current_timestamp > session_expiry;
+
+ Ok(expired)
+ }
+}
+
+#[instrument(skip_all)]
+pub async fn add_payment_method_data(
+ state: routes::AppState,
+ req: api::PaymentMethodCreate,
+ merchant_account: domain::MerchantAccount,
+ key_store: domain::MerchantKeyStore,
+ pm_id: String,
+) -> errors::RouterResponse<api::PaymentMethodResponse> {
+ let db = &*state.store;
+
+ let pmd = req
+ .payment_method_data
+ .clone()
+ .get_required_value("payment_method_data")?;
+ req.payment_method.get_required_value("payment_method")?;
+ let client_secret = req
+ .client_secret
+ .clone()
+ .get_required_value("client_secret")?;
+ let payment_method = db
+ .find_payment_method(pm_id.as_str(), merchant_account.storage_scheme)
+ .await
+ .change_context(errors::ApiErrorResponse::PaymentMethodNotFound)
+ .attach_printable("Unable to find payment method")?;
+
+ if payment_method.status != enums::PaymentMethodStatus::AwaitingData {
+ return Err((errors::ApiErrorResponse::DuplicatePaymentMethod).into());
+ }
+
+ let customer_id = payment_method.customer_id.clone();
+ let customer = db
+ .find_customer_by_customer_id_merchant_id(
+ customer_id.as_str(),
+ &merchant_account.merchant_id,
+ &key_store,
+ merchant_account.storage_scheme,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;
+
+ let client_secret_expired =
+ authenticate_pm_client_secret_and_check_expiry(&client_secret, &payment_method)?;
+
+ if client_secret_expired {
+ return Err((errors::ApiErrorResponse::ClientSecretExpired).into());
+ };
+
+ match pmd {
+ api_models::payment_methods::PaymentMethodCreateData::Card(card) => {
+ helpers::validate_card_expiry(&card.card_exp_month, &card.card_exp_year)?;
+ let resp = add_card_to_locker(
+ &state,
+ req.clone(),
+ &card,
+ &customer_id,
+ &merchant_account,
+ None,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError);
+
+ match resp {
+ Ok((mut pm_resp, duplication_check)) => {
+ if duplication_check.is_some() {
+ let pm_update = storage::PaymentMethodUpdate::StatusUpdate {
+ status: Some(enums::PaymentMethodStatus::Inactive),
+ };
+
+ db.update_payment_method(
+ payment_method,
+ pm_update,
+ merchant_account.storage_scheme,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to add payment method in db")?;
+
+ get_or_insert_payment_method(
+ db,
+ req.clone(),
+ &mut pm_resp,
+ &merchant_account,
+ &customer_id,
+ &key_store,
+ )
+ .await?;
+
+ return Ok(services::ApplicationResponse::Json(pm_resp));
+ } else {
+ let locker_id = pm_resp.payment_method_id.clone();
+ pm_resp.payment_method_id = pm_id.clone();
+ pm_resp.client_secret = Some(client_secret.clone());
+
+ let card_isin = card.card_number.clone().get_card_isin();
+
+ let card_info = db
+ .get_card_info(card_isin.as_str())
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to get card info")?;
+
+ let updated_card = CardDetailsPaymentMethod {
+ issuer_country: card_info
+ .as_ref()
+ .and_then(|ci| ci.card_issuing_country.clone()),
+ last4_digits: Some(card.card_number.clone().get_last4()),
+ expiry_month: Some(card.card_exp_month),
+ expiry_year: Some(card.card_exp_year),
+ nick_name: card.nick_name,
+ card_holder_name: card.card_holder_name,
+ card_network: card_info.as_ref().and_then(|ci| ci.card_network.clone()),
+ card_isin: Some(card_isin),
+ card_issuer: card_info.as_ref().and_then(|ci| ci.card_issuer.clone()),
+ card_type: card_info.as_ref().and_then(|ci| ci.card_type.clone()),
+ saved_to_locker: true,
+ };
+
+ let updated_pmd = Some(PaymentMethodsData::Card(updated_card));
+ let pm_data_encrypted =
+ create_encrypted_payment_method_data(&key_store, updated_pmd).await;
+
+ let pm_update = storage::PaymentMethodUpdate::AdditionalDataUpdate {
+ payment_method_data: pm_data_encrypted,
+ status: Some(enums::PaymentMethodStatus::Active),
+ locker_id: Some(locker_id),
+ payment_method: req.payment_method,
+ };
+
+ db.update_payment_method(
+ payment_method,
+ pm_update,
+ merchant_account.storage_scheme,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to add payment method in db")?;
+
+ if customer.default_payment_method_id.is_none() {
+ let _ = set_default_payment_method(
+ db,
+ merchant_account.merchant_id.clone(),
+ key_store.clone(),
+ customer_id.as_str(),
+ pm_id,
+ merchant_account.storage_scheme,
+ )
+ .await
+ .map_err(|err| logger::error!(error=?err,"Failed to set the payment method as default"));
+ }
+
+ return Ok(services::ApplicationResponse::Json(pm_resp));
+ }
+ }
+ Err(e) => {
+ let pm_update = storage::PaymentMethodUpdate::StatusUpdate {
+ status: Some(enums::PaymentMethodStatus::Inactive),
+ };
+
+ db.update_payment_method(
+ payment_method,
+ pm_update,
+ merchant_account.storage_scheme,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to update payment method in db")?;
+
+ return Err(e.attach_printable("Failed to add card to locker"));
+ }
+ }
+ }
+ }
+}
+
#[instrument(skip_all)]
pub async fn add_payment_method(
state: routes::AppState,
@@ -244,8 +500,9 @@ pub async fn add_payment_method(
let db = &*state.store;
let merchant_id = &merchant_account.merchant_id;
let customer_id = req.customer_id.clone().get_required_value("customer_id")?;
+ let payment_method = req.payment_method.get_required_value("payment_method")?;
- let response = match req.payment_method {
+ let response = match payment_method {
#[cfg(feature = "payouts")]
api_enums::PaymentMethod::BankTransfer => match req.bank_transfer.clone() {
Some(bank) => add_bank_to_locker(
@@ -402,8 +659,8 @@ pub async fn add_payment_method(
None => {
let pm_metadata = resp.metadata.as_ref().map(|data| data.peek());
- let locker_id = if resp.payment_method == api_enums::PaymentMethod::Card
- || resp.payment_method == api_enums::PaymentMethod::BankTransfer
+ let locker_id = if resp.payment_method == Some(api_enums::PaymentMethod::Card)
+ || resp.payment_method == Some(api_enums::PaymentMethod::BankTransfer)
{
Some(resp.payment_method_id)
} else {
@@ -463,6 +720,7 @@ pub async fn insert_payment_method(
pm_data_encrypted,
key_store,
connector_mandate_details,
+ None,
network_transaction_id,
storage_scheme,
)
@@ -554,6 +812,8 @@ pub async fn update_customer_payment_method(
wallet: req.wallet,
metadata: req.metadata,
customer_id: Some(pm.customer_id.clone()),
+ client_secret: None,
+ payment_method_data: None,
card_network: req
.card_network
.as_ref()
@@ -641,6 +901,7 @@ pub async fn update_customer_payment_method(
installment_payment_enabled: false,
payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]),
last_used_at: Some(common_utils::date_time::now()),
+ client_secret: None,
}
};
@@ -1602,7 +1863,7 @@ pub async fn list_payment_methods(
let customer_wallet_pm = customer_payment_methods
.iter()
.filter(|cust_pm| {
- cust_pm.payment_method == enums::PaymentMethod::Wallet
+ cust_pm.payment_method == Some(enums::PaymentMethod::Wallet)
})
.collect::<Vec<_>>();
@@ -3029,7 +3290,9 @@ pub async fn list_customer_payment_method(
for pm in resp.into_iter() {
let parent_payment_method_token = generate_id(consts::ID_LENGTH, "token");
- let payment_method_retrieval_context = match pm.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, key, state).await?;
@@ -3111,7 +3374,7 @@ pub async fn list_customer_payment_method(
};
// Retrieve the masked bank details to be sent as a response
- let bank_details = if pm.payment_method == enums::PaymentMethod::BankDebit {
+ let bank_details = if payment_method == enums::PaymentMethod::BankDebit {
get_masked_bank_details(&pm, key)
.await
.unwrap_or_else(|err| {
@@ -3128,7 +3391,7 @@ pub async fn list_customer_payment_method(
payment_token: parent_payment_method_token.to_owned(),
payment_method_id: pm.payment_method_id.clone(),
customer_id: pm.customer_id,
- payment_method: pm.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,
@@ -3432,9 +3695,14 @@ async fn get_bank_account_connector_details(
.get_required_value("payment_method_type")
.attach_printable("PaymentMethodType not found")?;
+ let pm = pm
+ .payment_method
+ .get_required_value("payment_method")
+ .attach_printable("PaymentMethod not found")?;
+
let token_data = BankAccountTokenData {
payment_method_type: pm_type,
- payment_method: pm.payment_method,
+ payment_method: pm,
connector_details: connector_details.clone(),
};
@@ -3467,6 +3735,9 @@ pub async fn set_default_payment_method(
.find_payment_method(&payment_method_id, storage_scheme)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
+ let pm = payment_method
+ .payment_method
+ .get_required_value("payment_method")?;
utils::when(
payment_method.customer_id != customer_id || payment_method.merchant_id != merchant_id,
@@ -3505,11 +3776,12 @@ pub async fn set_default_payment_method(
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update the default payment method id for the customer")?;
+
let resp = CustomerDefaultPaymentMethodResponse {
default_payment_method_id: updated_customer_details.default_payment_method_id,
customer_id,
payment_method_type: payment_method.payment_method_type,
- payment_method: payment_method.payment_method,
+ payment_method: pm,
};
Ok(services::ApplicationResponse::Json(resp))
@@ -3689,7 +3961,7 @@ pub async fn retrieve_payment_method(
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
let key = key_store.key.peek();
- let card = if pm.payment_method == enums::PaymentMethod::Card {
+ 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,
@@ -3726,6 +3998,7 @@ pub async fn retrieve_payment_method(
installment_payment_enabled: false,
payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]),
last_used_at: Some(pm.last_used_at),
+ client_secret: pm.client_secret,
},
))
}
@@ -3773,7 +4046,7 @@ pub async fn delete_payment_method(
|| Err(errors::ApiErrorResponse::PaymentMethodDeleteFailed),
)?;
- if key.payment_method == enums::PaymentMethod::Card {
+ if key.payment_method == Some(enums::PaymentMethod::Card) {
let response = delete_card_from_locker(
&state,
&key.customer_id,
diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs
index a9671cc6783..749508c9740 100644
--- a/crates/router/src/core/payment_methods/transformers.rs
+++ b/crates/router/src/core/payment_methods/transformers.rs
@@ -328,6 +328,7 @@ pub fn mk_add_bank_response_hs(
installment_payment_enabled: false, // #[#256]
payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]),
last_used_at: Some(common_utils::date_time::now()),
+ client_secret: None,
}
}
@@ -373,6 +374,7 @@ pub fn mk_add_card_response_hs(
installment_payment_enabled: false, // #[#256]
payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]),
last_used_at: Some(common_utils::date_time::now()), // [#256]
+ client_secret: None,
}
}
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index a3292e3cd69..b9a8795aa54 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -3366,7 +3366,7 @@ pub fn is_network_transaction_id_flow(
.connector_list;
pg_agnostic == "true"
- && payment_method_info.payment_method == storage_enums::PaymentMethod::Card
+ && payment_method_info.payment_method == Some(storage_enums::PaymentMethod::Card)
&& ntid_supported_connectors.contains(&connector)
&& payment_method_info.network_transaction_id.is_some()
}
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 48a6d411780..de2fdd99b7b 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -486,7 +486,7 @@ pub async fn get_token_pm_type_mandate_details(
(
None,
- Some(payment_method_info.payment_method),
+ payment_method_info.payment_method,
payment_method_info.payment_method_type,
None,
None,
@@ -635,7 +635,7 @@ pub async fn get_token_for_recurring_mandate(
merchant_connector_id: mandate.merchant_connector_id,
};
- if let diesel_models::enums::PaymentMethod::Card = payment_method.payment_method {
+ if let Some(diesel_models::enums::PaymentMethod::Card) = payment_method.payment_method {
if state.conf.locker.locker_enabled {
let _ = cards::get_lookup_key_from_locker(
state,
@@ -648,11 +648,14 @@ pub async fn get_token_for_recurring_mandate(
if let Some(payment_method_from_request) = req.payment_method {
let pm: storage_enums::PaymentMethod = payment_method_from_request;
- if pm != payment_method.payment_method {
+ if payment_method
+ .payment_method
+ .is_some_and(|payment_method| payment_method != pm)
+ {
Err(report!(errors::ApiErrorResponse::PreconditionFailed {
message:
"payment method in request does not match previously provided payment \
- method information"
+ method information"
.into()
}))?
}
@@ -660,7 +663,7 @@ pub async fn get_token_for_recurring_mandate(
Ok(MandateGenericData {
token: Some(token),
- payment_method: Some(payment_method.payment_method),
+ payment_method: payment_method.payment_method,
recurring_mandate_payment_data: Some(payments::RecurringMandatePaymentData {
payment_method_type,
original_payment_authorized_amount,
@@ -674,7 +677,7 @@ pub async fn get_token_for_recurring_mandate(
} else {
Ok(MandateGenericData {
token: None,
- payment_method: Some(payment_method.payment_method),
+ payment_method: payment_method.payment_method,
recurring_mandate_payment_data: Some(payments::RecurringMandatePaymentData {
payment_method_type,
original_payment_authorized_amount,
@@ -1264,7 +1267,7 @@ pub(crate) async fn get_payment_method_create_request(
};
let customer_id = customer.customer_id.clone();
let payment_method_request = api::PaymentMethodCreate {
- payment_method,
+ payment_method: Some(payment_method),
payment_method_type,
payment_method_issuer: card.card_issuer.clone(),
payment_method_issuer_code: None,
@@ -1279,12 +1282,14 @@ pub(crate) async fn get_payment_method_create_request(
.card_network
.as_ref()
.map(|card_network| card_network.to_string()),
+ client_secret: None,
+ payment_method_data: None,
};
Ok(payment_method_request)
}
_ => {
let payment_method_request = api::PaymentMethodCreate {
- payment_method,
+ payment_method: Some(payment_method),
payment_method_type,
payment_method_issuer: None,
payment_method_issuer_code: None,
@@ -1296,6 +1301,8 @@ pub(crate) async fn get_payment_method_create_request(
metadata: None,
customer_id: Some(customer.customer_id.to_owned()),
card_network: None,
+ client_secret: None,
+ payment_method_data: None,
};
Ok(payment_method_request)
@@ -1900,7 +1907,7 @@ pub async fn make_pm_data<'a, F: Clone, R, Ctx: PaymentMethodRetrieve>(
if payment_data.token_data.is_none() {
if let Some(payment_method_info) = &payment_data.payment_method_info {
- if payment_method_info.payment_method == storage_enums::PaymentMethod::Card {
+ if payment_method_info.payment_method == Some(storage_enums::PaymentMethod::Card) {
payment_data.token_data =
Some(storage::PaymentTokenData::PermanentCard(CardTokenData {
payment_method_id: Some(payment_method_info.payment_method_id.clone()),
diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs
index 62acfb449eb..5bf6b2e7013 100644
--- a/crates/router/src/core/payments/tokenization.rs
+++ b/crates/router/src/core/payments/tokenization.rs
@@ -306,6 +306,7 @@ where
pm_data_encrypted,
key_store,
connector_mandate_details,
+ None,
network_transaction_id,
merchant_account.storage_scheme,
)
@@ -503,11 +504,13 @@ where
None => {
let pm_metadata = create_payment_method_metadata(None, connector_token)?;
- locker_id = if resp.payment_method == PaymentMethod::Card {
- Some(resp.payment_method_id)
- } else {
- None
- };
+ locker_id = resp.payment_method.and_then(|pm| {
+ if pm == PaymentMethod::Card {
+ Some(resp.payment_method_id)
+ } else {
+ None
+ }
+ });
resp.payment_method_id = generate_id(consts::ID_LENGTH, "pm");
payment_methods::cards::create_payment_method(
@@ -522,6 +525,7 @@ where
pm_data_encrypted,
key_store,
connector_mandate_details,
+ None,
network_transaction_id,
merchant_account.storage_scheme,
)
@@ -598,6 +602,7 @@ async fn skip_saving_card_in_locker(
#[cfg(feature = "payouts")]
bank_transfer: None,
last_used_at: Some(common_utils::date_time::now()),
+ client_secret: None,
};
Ok((pm_resp, None))
@@ -619,6 +624,7 @@ async fn skip_saving_card_in_locker(
#[cfg(feature = "payouts")]
bank_transfer: None,
last_used_at: Some(common_utils::date_time::now()),
+ client_secret: None,
};
Ok((payment_method_response, None))
}
@@ -668,6 +674,7 @@ pub async fn save_in_locker(
installment_payment_enabled: false, //[#219]
payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), //[#219]
last_used_at: Some(common_utils::date_time::now()),
+ client_secret: None,
};
Ok((payment_method_response, None))
}
diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs
index 8280ddb6c2f..e521fac9a80 100644
--- a/crates/router/src/core/payouts/helpers.rs
+++ b/crates/router/src/core/payouts/helpers.rs
@@ -376,9 +376,9 @@ pub async fn save_payout_data_to_locker(
.map(|c| c.card_number.clone().get_card_isin());
let mut payment_method = api::PaymentMethodCreate {
- payment_method: api_enums::PaymentMethod::foreign_from(
+ payment_method: Some(api_enums::PaymentMethod::foreign_from(
payout_method_data.to_owned(),
- ),
+ )),
payment_method_type: Some(payment_method_type),
payment_method_issuer: None,
payment_method_issuer_code: None,
@@ -388,6 +388,8 @@ pub async fn save_payout_data_to_locker(
metadata: None,
customer_id: Some(payout_attempt.customer_id.to_owned()),
card_network: None,
+ client_secret: None,
+ payment_method_data: None,
};
let pm_data = card_isin
@@ -455,9 +457,9 @@ pub async fn save_payout_data_to_locker(
(
None,
api::PaymentMethodCreate {
- payment_method: api_enums::PaymentMethod::foreign_from(
+ payment_method: Some(api_enums::PaymentMethod::foreign_from(
payout_method_data.to_owned(),
- ),
+ )),
payment_method_type: Some(payment_method_type),
payment_method_issuer: None,
payment_method_issuer_code: None,
@@ -467,6 +469,8 @@ pub async fn save_payout_data_to_locker(
metadata: None,
customer_id: Some(payout_attempt.customer_id.to_owned()),
card_network: None,
+ client_secret: None,
+ payment_method_data: None,
},
)
};
@@ -487,6 +491,7 @@ pub async fn save_payout_data_to_locker(
key_store,
None,
None,
+ None,
merchant_account.storage_scheme,
)
.await?;
diff --git a/crates/router/src/core/pm_auth.rs b/crates/router/src/core/pm_auth.rs
index 09b8ad9f868..6d5ae7a08c3 100644
--- a/crates/router/src/core/pm_auth.rs
+++ b/crates/router/src/core/pm_auth.rs
@@ -311,7 +311,7 @@ async fn store_bank_details_in_payment_methods(
> = HashMap::new();
for pm in payment_methods {
- if pm.payment_method == enums::PaymentMethod::BankDebit {
+ if pm.payment_method == Some(enums::PaymentMethod::BankDebit) {
let bank_details_pm_data = decrypt::<serde_json::Value, masking::WithType>(
pm.payment_method_data.clone(),
key,
@@ -442,7 +442,7 @@ async fn store_bank_details_in_payment_methods(
customer_id: customer_id.clone(),
merchant_id: merchant_account.merchant_id.clone(),
payment_method_id: pm_id,
- payment_method: enums::PaymentMethod::BankDebit,
+ payment_method: Some(enums::PaymentMethod::BankDebit),
payment_method_type: Some(creds.payment_method_type),
payment_method_issuer: None,
scheme: None,
diff --git a/crates/router/src/db/payment_method.rs b/crates/router/src/db/payment_method.rs
index 72676ca81ee..528861a70aa 100644
--- a/crates/router/src/db/payment_method.rs
+++ b/crates/router/src/db/payment_method.rs
@@ -660,6 +660,7 @@ impl PaymentMethodInterface for MockDb {
connector_mandate_details: payment_method_new.connector_mandate_details,
customer_acceptance: payment_method_new.customer_acceptance,
status: payment_method_new.status,
+ client_secret: payment_method_new.client_secret,
network_transaction_id: payment_method_new.network_transaction_id,
};
payment_methods.push(payment_method.clone());
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 2771ee42947..ff660dbf7b7 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -782,6 +782,10 @@ impl PaymentMethods {
web::resource("/{payment_method_id}/update")
.route(web::post().to(payment_method_update_api)),
)
+ .service(
+ web::resource("/{payment_method_id}/save")
+ .route(web::post().to(save_payment_method_api)),
+ )
.service(
web::resource("/auth/link").route(web::post().to(pm_auth::link_token_create)),
)
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index 8e29b28fb66..aec3a5f2c1f 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -99,7 +99,8 @@ impl From<Flow> for ApiIdentifier {
| Flow::PaymentMethodsDelete
| Flow::ValidatePaymentMethod
| Flow::ListCountriesCurrencies
- | Flow::DefaultPaymentMethodsSet => Self::PaymentMethods,
+ | Flow::DefaultPaymentMethodsSet
+ | Flow::PaymentMethodSave => Self::PaymentMethods,
Flow::PmAuthLinkTokenCreate | Flow::PmAuthExchangeToken => Self::PaymentMethodAuth,
diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs
index a5ffcdabe33..e9dacd9f84f 100644
--- a/crates/router/src/routes/payment_methods.rs
+++ b/crates/router/src/routes/payment_methods.rs
@@ -23,13 +23,14 @@ pub async fn create_payment_method_api(
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(cards::add_payment_method(
+ Box::pin(cards::get_client_secret_or_add_payment_method(
state,
req,
&auth.merchant_account,
@@ -43,6 +44,41 @@ pub async fn create_payment_method_api(
.await
}
+#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodSave))]
+pub async fn save_payment_method_api(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ json_payload: web::Json<payment_methods::PaymentMethodCreate>,
+ path: web::Path<String>,
+) -> HttpResponse {
+ let flow = Flow::PaymentMethodSave;
+ let payload = json_payload.into_inner();
+ let pm_id = path.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),
+ };
+
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ payload,
+ |state, auth, req, _| {
+ Box::pin(cards::add_payment_method_data(
+ state,
+ req,
+ auth.merchant_account,
+ auth.key_store,
+ pm_id.clone(),
+ ))
+ },
+ &*auth,
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsList))]
pub async fn list_payment_method_api(
state: web::Data<AppState>,
diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs
index b04d3f3b6f6..5203b20c55b 100644
--- a/crates/router/src/services/authentication.rs
+++ b/crates/router/src/services/authentication.rs
@@ -1,5 +1,8 @@
use actix_web::http::header::HeaderMap;
-use api_models::{payment_methods::PaymentMethodListRequest, payments};
+use api_models::{
+ payment_methods::{PaymentMethodCreate, PaymentMethodListRequest},
+ payments,
+};
use async_trait::async_trait;
use common_utils::date_time;
use error_stack::{report, ResultExt};
@@ -832,6 +835,12 @@ impl ClientSecretFetch for PaymentMethodListRequest {
}
}
+impl ClientSecretFetch for PaymentMethodCreate {
+ fn get_client_secret(&self) -> Option<&String> {
+ self.client_secret.as_ref()
+ }
+}
+
impl ClientSecretFetch for api_models::cards_info::CardsInfoRequest {
fn get_client_secret(&self) -> Option<&String> {
self.client_secret.as_ref()
diff --git a/crates/router/src/types/api/mandates.rs b/crates/router/src/types/api/mandates.rs
index dda6dc0cfcc..0e80fd224da 100644
--- a/crates/router/src/types/api/mandates.rs
+++ b/crates/router/src/types/api/mandates.rs
@@ -1,5 +1,6 @@
use api_models::mandates;
pub use api_models::mandates::{MandateId, MandateResponse, MandateRevokedResponse};
+use common_utils::ext_traits::OptionExt;
use error_stack::ResultExt;
use masking::PeekInterface;
use serde::{Deserialize, Serialize};
@@ -46,7 +47,13 @@ impl MandateResponseExt for MandateResponse {
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
- let card = if payment_method.payment_method == storage_enums::PaymentMethod::Card {
+ 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(
@@ -95,7 +102,7 @@ impl MandateResponseExt for MandateResponse {
}),
card,
status: mandate.mandate_status,
- payment_method: payment_method.payment_method.to_string(),
+ payment_method: pm.to_string(),
payment_method_type,
payment_method_id: mandate.payment_method_id,
})
diff --git a/crates/router/src/types/api/payment_methods.rs b/crates/router/src/types/api/payment_methods.rs
index 13c9ec61f2a..6bf100e4d67 100644
--- a/crates/router/src/types/api/payment_methods.rs
+++ b/crates/router/src/types/api/payment_methods.rs
@@ -2,8 +2,8 @@ pub use api_models::payment_methods::{
CardDetail, CardDetailFromLocker, CardDetailsPaymentMethod, CustomerPaymentMethod,
CustomerPaymentMethodsListResponse, DefaultPaymentMethod, DeleteTokenizeByTokenRequest,
GetTokenizePayloadRequest, GetTokenizePayloadResponse, ListCountriesCurrenciesRequest,
- PaymentMethodCreate, PaymentMethodDeleteResponse, PaymentMethodId, PaymentMethodList,
- PaymentMethodListRequest, PaymentMethodListResponse, PaymentMethodResponse,
+ PaymentMethodCreate, PaymentMethodCreateData, PaymentMethodDeleteResponse, PaymentMethodId,
+ PaymentMethodList, PaymentMethodListRequest, PaymentMethodListResponse, PaymentMethodResponse,
PaymentMethodUpdate, PaymentMethodsData, TokenizePayloadEncrypted, TokenizePayloadRequest,
TokenizedCardValue1, TokenizedCardValue2, TokenizedWalletValue1, TokenizedWalletValue2,
};
@@ -21,15 +21,14 @@ pub(crate) trait PaymentMethodCreateExt {
// convert self.payment_method_type to payment_method and compare it against self.payment_method
impl PaymentMethodCreateExt for PaymentMethodCreate {
fn validate(&self) -> RouterResult<()> {
- if let Some(payment_method_type) = self.payment_method_type {
- if !validate_payment_method_type_against_payment_method(
- self.payment_method,
- payment_method_type,
- ) {
- return Err(report!(errors::ApiErrorResponse::InvalidRequestData {
- message: "Invalid 'payment_method_type' provided".to_string()
- })
- .attach_printable("Invalid payment method type"));
+ if let Some(pm) = self.payment_method {
+ if let Some(payment_method_type) = self.payment_method_type {
+ if !validate_payment_method_type_against_payment_method(pm, payment_method_type) {
+ return Err(report!(errors::ApiErrorResponse::InvalidRequestData {
+ message: "Invalid 'payment_method_type' provided".to_string()
+ })
+ .attach_printable("Invalid payment method type"));
+ }
}
}
Ok(())
diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs
index d0cd2b7a11d..6ecd53afaed 100644
--- a/crates/router/src/types/transformers.rs
+++ b/crates/router/src/types/transformers.rs
@@ -1,6 +1,9 @@
// use actix_web::HttpMessage;
use actix_web::http::header::HeaderMap;
-use api_models::{enums as api_enums, gsm as gsm_api_types, payments, routing::ConnectorSelection};
+use api_models::{
+ enums as api_enums, gsm as gsm_api_types, payment_methods, payments,
+ routing::ConnectorSelection,
+};
use common_utils::{
consts::X_HS_LATENCY,
crypto::Encryptable,
@@ -71,6 +74,28 @@ impl ForeignFrom<api_models::refunds::RefundType> for storage_enums::RefundType
}
}
+impl ForeignFrom<diesel_models::PaymentMethod> for payment_methods::PaymentMethodResponse {
+ fn foreign_from(item: diesel_models::PaymentMethod) -> Self {
+ Self {
+ merchant_id: item.merchant_id,
+ customer_id: Some(item.customer_id),
+ payment_method_id: item.payment_method_id,
+ payment_method: item.payment_method,
+ payment_method_type: item.payment_method_type,
+ card: None,
+ recurring_enabled: false,
+ installment_payment_enabled: false,
+ payment_experience: None,
+ metadata: item.metadata,
+ created: Some(item.created_at),
+ #[cfg(feature = "payouts")]
+ bank_transfer: None,
+ last_used_at: None,
+ client_secret: item.client_secret,
+ }
+ }
+}
+
impl ForeignFrom<storage_enums::AttemptStatus> for storage_enums::IntentStatus {
fn foreign_from(s: storage_enums::AttemptStatus) -> Self {
match s {
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index 991db38635b..0ec6894debe 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -113,6 +113,8 @@ pub enum Flow {
PaymentMethodsCreate,
/// Payment methods list flow.
PaymentMethodsList,
+ /// Payment method save flow
+ PaymentMethodSave,
/// Customer payment methods list flow.
CustomerPaymentMethodsList,
/// List Customers for a merchant
diff --git a/migrations/2024-03-15-133951_pm-client-secret/down.sql b/migrations/2024-03-15-133951_pm-client-secret/down.sql
new file mode 100644
index 00000000000..90b2d0dba14
--- /dev/null
+++ b/migrations/2024-03-15-133951_pm-client-secret/down.sql
@@ -0,0 +1,3 @@
+-- This file should undo anything in `up.sql`
+ALTER TABLE payment_methods DROP COLUMN IF EXISTS client_secret;
+ALTER TABLE payment_methods ALTER COLUMN payment_method SET NOT NULL;
\ No newline at end of file
diff --git a/migrations/2024-03-15-133951_pm-client-secret/up.sql b/migrations/2024-03-15-133951_pm-client-secret/up.sql
new file mode 100644
index 00000000000..e933d3ff382
--- /dev/null
+++ b/migrations/2024-03-15-133951_pm-client-secret/up.sql
@@ -0,0 +1,3 @@
+-- Your SQL goes here
+ALTER TABLE payment_methods ADD COLUMN IF NOT EXISTS client_secret VARCHAR(128) DEFAULT NULL;
+ALTER TABLE payment_methods ALTER COLUMN payment_method DROP NOT NULL;
\ No newline at end of file
diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json
index f646ba8b8d9..0bc0059e949 100644
--- a/openapi/openapi_spec.json
+++ b/openapi/openapi_spec.json
@@ -12498,10 +12498,38 @@
}
],
"nullable": true
+ },
+ "client_secret": {
+ "type": "string",
+ "description": "For Client based calls, SDK will use the client_secret\nin order to call /payment_methods\nClient secret will be generated whenever a new\npayment method is created",
+ "nullable": true
+ },
+ "payment_method_data": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/PaymentMethodCreateData"
+ }
+ ],
+ "nullable": true
}
},
"additionalProperties": false
},
+ "PaymentMethodCreateData": {
+ "oneOf": [
+ {
+ "type": "object",
+ "required": [
+ "card"
+ ],
+ "properties": {
+ "card": {
+ "$ref": "#/components/schemas/CardDetail"
+ }
+ }
+ }
+ ]
+ },
"PaymentMethodData": {
"oneOf": [
{
@@ -12887,6 +12915,11 @@
"format": "date-time",
"example": "2024-02-24T11:04:09.922Z",
"nullable": true
+ },
+ "client_secret": {
+ "type": "string",
+ "description": "For Client based calls",
+ "nullable": true
}
}
},
@@ -12895,7 +12928,8 @@
"enum": [
"active",
"inactive",
- "processing"
+ "processing",
+ "awaiting_data"
]
},
"PaymentMethodType": {
|
2024-03-19T14:34: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 -->
**Vaulting without authentication in a non-payments context.**
This PR enables -
- client_secret auth for `/payment_methods` (Generation and storage of client_secret)
- Vaulting of payment_method with client_secret auth using `/payment_methods/:pm_id/save`
- Making payment_method a nullable in schema
### Additional Changes
- [x] 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)?
-->
1. Create a customer
```
curl --location --request POST 'http://localhost:8080/customers' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_y5XDvbHKvRI6K2dAhTgXvNgQykJiqLXeYtSysCQzPGBGz3RZoUPjPcfD1LW8teYO' \
--data-raw '{
"email": "guest@example.com",
"name": "John Doe1",
"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
```
curl --location --request POST 'http://localhost:8080/payment_methods' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_63yd7Y0i2CvRcJYKfXcIE8wAva0b5YMtKHr6oTpcnggVmWqsK0Q6CvoKB1WiXoTz' \
--data-raw '{
"customer_id": "cus_RHnmMuG8mKhICwigyUeP"
}'
```
Response -
```
{
"merchant_id": "sarthak",
"customer_id": "cus_RHnmMuG8mKhICwigyUeP",
"payment_method_id": "pm_DC74n7ocq8SKGvNVai0M",
"payment_method": null,
"payment_method_type": null,
"card": null,
"recurring_enabled": false,
"installment_payment_enabled": false,
"payment_experience": null,
"metadata": null,
"created": null,
"last_used_at": null,
"client_secret": "pm_DC74n7ocq8SKGvNVai0M_secret_9wUZYKaUcORN13IdGCOo"
}
```
DB entry -
<img width="1512" alt="image" src="https://github.com/juspay/hyperswitch/assets/76486416/97359e0a-0979-4c98-844e-cb3887adfaf0">
3. Save the payment method with client_secret
```
curl --location --request POST 'http://localhost:8080/payment_methods/pm_DC74n7ocq8SKGvNVai0M/save' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: pk_dev_660e47ec672f43849d6b0403fcaf76ac' \
--data-raw '{
"payment_method": "card",
"client_secret": "pm_DC74n7ocq8SKGvNVai0M_secret_9wUZYKaUcORN13IdGCOo",
"customer_id": "cus_RHnmMuG8mKhICwigyUeP",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "10",
"card_exp_year": "2026",
"card_holder_name": "joseph"
}
}
}'
```
Response -
```
{
"merchant_id": "sarthak",
"customer_id": "cus_RHnmMuG8mKhICwigyUeP",
"payment_method_id": "pm_DC74n7ocq8SKGvNVai0M",
"payment_method": "card",
"payment_method_type": null,
"card": {
"scheme": null,
"issuer_country": null,
"last4_digits": "4242",
"expiry_month": "10",
"expiry_year": "2026",
"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-04-03T13:02:00.926Z",
"last_used_at": "2024-04-03T13:02:00.926Z",
"client_secret": "pm_DC74n7ocq8SKGvNVai0M_secret_9wUZYKaUcORN13IdGCOo"
}
```
DB entry -
<img width="1512" alt="image" src="https://github.com/juspay/hyperswitch/assets/76486416/e4eea6ea-2223-4ef9-a631-d316c8777fbe">
## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
e458e4907e39961f386900f21382c9ace3b7c392
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4090
|
Bug: [BUG]: Stripe API version should be passed in the API headers
### Bug Description
Stripe supports multiple api versions and each stripe merchant account has its own default api version based on the time the account has created. So whenever Hyperswitch calls stripe API, stripe will respond based on merchant's default version which might differ from the version which Hyperswitch has implemented. This can be avoided by passing version which was implemented at Hyperswitch in the headers while calling Stripe API's. For more info - https://docs.stripe.com/api/versioning
### Expected Behavior
Stripe Merchant account with any API version as default should be able to use Stripe integration with Hyperswitch
### Actual Behavior
Deserialization error
### 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/connector/stripe.rs b/crates/router/src/connector/stripe.rs
index 7718c2fc729..958867465f9 100644
--- a/crates/router/src/connector/stripe.rs
+++ b/crates/router/src/connector/stripe.rs
@@ -7,6 +7,7 @@ use diesel_models::enums;
use error_stack::{IntoReport, ResultExt};
use masking::PeekInterface;
use router_env::{instrument, tracing};
+use stripe::auth_headers;
use self::transformers as stripe;
use super::utils::{self as connector_utils, RefundsRequestData};
@@ -55,10 +56,16 @@ impl ConnectorCommon for Stripe {
let auth: stripe::StripeAuthType = auth_type
.try_into()
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
- Ok(vec![(
- headers::AUTHORIZATION.to_string(),
- format!("Bearer {}", auth.api_key.peek()).into_masked(),
- )])
+ Ok(vec![
+ (
+ headers::AUTHORIZATION.to_string(),
+ format!("Bearer {}", auth.api_key.peek()).into_masked(),
+ ),
+ (
+ auth_headers::STRIPE_API_VERSION.to_string(),
+ auth_headers::STRIPE_VERSION.to_string().into_masked(),
+ ),
+ ])
}
}
diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs
index 45e2c795a0d..719710b602b 100644
--- a/crates/router/src/connector/stripe/transformers.rs
+++ b/crates/router/src/connector/stripe/transformers.rs
@@ -32,6 +32,11 @@ use crate::{
utils::OptionExt,
};
+pub mod auth_headers {
+ pub const STRIPE_API_VERSION: &str = "stripe-version";
+ pub const STRIPE_VERSION: &str = "2023-10-16";
+}
+
pub struct StripeAuthType {
pub(super) api_key: Secret<String>,
}
|
2024-03-15T10:16:44Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
Fixes https://github.com/juspay/hyperswitch/issues/4090
### 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 stripe Card Payment Request
```
{
"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_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": "sundari"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "sundari"
}
},
"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"
}
}
```
Response
```
{
"payment_id": "pay_cmmd8900wIRqd11y6kUL",
"merchant_id": "postman_merchant_GHAction_8953df12-7ed3-416a-9334-4c71f3e2672d",
"status": "succeeded",
"amount": 6540,
"net_amount": 6540,
"amount_capturable": 0,
"amount_received": 6540,
"connector": "stripe",
"client_secret": "pay_cmmd8900wIRqd11y6kUL_secret_gcsfaLqv8d1pMAq6xApL",
"created": "2024-03-15T10:59:51.115Z",
"currency": "INR",
"customer_id": "StripeCustomer",
"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": "42424242",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe"
},
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "sundari",
"last_name": null
},
"phone": {
"number": null,
"country_code": null
},
"email": 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": "sundari",
"last_name": null
},
"phone": {
"number": null,
"country_code": null
},
"email": null
},
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "94122",
"state": "California",
"first_name": "sundari",
"last_name": null
},
"phone": {
"number": null,
"country_code": null
},
"email": null
},
"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": null,
"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": 1710500391,
"expires": 1710503991,
"secret": "epk_c5c1acf2bee0476182e5c46bcc1079c5"
},
"manual_retry_allowed": false,
"connector_transaction_id": "pi_3OuYUND5R7gDAGff1bwg1RSP",
"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_3OuYUND5R7gDAGff1bwg1RSP",
"payment_link": null,
"profile_id": "pro_2x6hcEAjCQmaYxIpxO5V",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_IGo3sNcqXv7xd4POhiLS",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-03-15T11:14:51.115Z",
"fingerprint": null,
"payment_method_id": null,
"payment_method_status": null
}
```
Now in Stripe Dashboard search for the payment Under Developer -> Logs using `connector_transaction_id`
For that payment check the header-info , API-Version should be `"2023-10-16"`
## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
0f6c97c47ddd0980ace13840faadc4b6eefaa48e
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4098
|
Bug: Merchant PML to return only PM API compatible PMs
The `/account/payment_methods` should list only the _Add Payment Method_ flow compatible PMs if invoked with the `PM Client Secret` authentication.
This is to weed out PMs which cannot be saved without making a payment/setting up a recurring payment/mandate.
For example, to saving wallet PMs like Apple Pay would always require to create a mandate with the connector and hence need not be shown to the customer in the Add Payment Method flow.
|
diff --git a/config/config.example.toml b/config/config.example.toml
index b2e1fe3c458..b5585a84b32 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -613,3 +613,6 @@ payment_attempts = "hyperswitch-payment-attempt-events"
payment_intents = "hyperswitch-payment-intent-events"
refunds = "hyperswitch-refund-events"
disputes = "hyperswitch-dispute-events"
+
+[saved_payment_methods]
+sdk_eligible_payment_methods = ["card"]
\ No newline at end of file
diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml
index 8edfef7485e..fe47b10b543 100644
--- a/config/deployments/integration_test.toml
+++ b/config/deployments/integration_test.toml
@@ -319,3 +319,6 @@ connectors_with_webhook_source_verification_call = "paypal" # List of co
[unmasked_headers]
keys = "user-agent"
+
+[saved_payment_methods]
+sdk_eligible_payment_methods = ["card"]
\ No newline at end of file
diff --git a/config/deployments/production.toml b/config/deployments/production.toml
index 12724485ea1..3135b3d5682 100644
--- a/config/deployments/production.toml
+++ b/config/deployments/production.toml
@@ -330,3 +330,6 @@ connectors_with_webhook_source_verification_call = "paypal" # List of connec
[unmasked_headers]
keys = "user-agent"
+
+[saved_payment_methods]
+sdk_eligible_payment_methods = ["card"]
\ No newline at end of file
diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml
index 6c830c389a6..921301ebd6f 100644
--- a/config/deployments/sandbox.toml
+++ b/config/deployments/sandbox.toml
@@ -334,3 +334,6 @@ connectors_with_webhook_source_verification_call = "paypal" # List of con
[unmasked_headers]
keys = "user-agent"
+
+[saved_payment_methods]
+sdk_eligible_payment_methods = ["card"]
\ No newline at end of file
diff --git a/config/development.toml b/config/development.toml
index 92e13f24fec..db7f1ed93f4 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -615,3 +615,6 @@ payment_attempts = "hyperswitch-payment-attempt-events"
payment_intents = "hyperswitch-payment-intent-events"
refunds = "hyperswitch-refund-events"
disputes = "hyperswitch-dispute-events"
+
+[saved_payment_methods]
+sdk_eligible_payment_methods = ["card"]
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index d99ab473501..702d134f2d5 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -474,3 +474,6 @@ payment_attempts = "hyperswitch-payment-attempt-events"
payment_intents = "hyperswitch-payment-intent-events"
refunds = "hyperswitch-refund-events"
disputes = "hyperswitch-dispute-events"
+
+[saved_payment_methods]
+sdk_eligible_payment_methods = ["card"]
\ No newline at end of file
diff --git a/crates/diesel_models/src/payment_method.rs b/crates/diesel_models/src/payment_method.rs
index e2807f3b5ea..262848e1d55 100644
--- a/crates/diesel_models/src/payment_method.rs
+++ b/crates/diesel_models/src/payment_method.rs
@@ -143,6 +143,8 @@ pub enum PaymentMethodUpdate {
status: Option<storage_enums::PaymentMethodStatus>,
locker_id: Option<String>,
payment_method: Option<storage_enums::PaymentMethod>,
+ payment_method_type: Option<storage_enums::PaymentMethodType>,
+ payment_method_issuer: Option<String>,
},
ConnectorMandateDetailsUpdate {
connector_mandate_details: Option<serde_json::Value>,
@@ -162,6 +164,8 @@ pub struct PaymentMethodUpdateInternal {
locker_id: Option<String>,
payment_method: Option<storage_enums::PaymentMethod>,
connector_mandate_details: Option<serde_json::Value>,
+ payment_method_type: Option<storage_enums::PaymentMethodType>,
+ payment_method_issuer: Option<String>,
}
impl PaymentMethodUpdateInternal {
@@ -208,6 +212,8 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
locker_id: None,
payment_method: None,
connector_mandate_details: None,
+ payment_method_issuer: None,
+ payment_method_type: None,
},
PaymentMethodUpdate::PaymentMethodDataUpdate {
payment_method_data,
@@ -220,6 +226,8 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
locker_id: None,
payment_method: None,
connector_mandate_details: None,
+ payment_method_issuer: None,
+ payment_method_type: None,
},
PaymentMethodUpdate::LastUsedUpdate { last_used_at } => Self {
metadata: None,
@@ -230,6 +238,8 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
locker_id: None,
payment_method: None,
connector_mandate_details: None,
+ payment_method_issuer: None,
+ payment_method_type: None,
},
PaymentMethodUpdate::NetworkTransactionIdAndStatusUpdate {
network_transaction_id,
@@ -243,6 +253,8 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
locker_id: None,
payment_method: None,
connector_mandate_details: None,
+ payment_method_issuer: None,
+ payment_method_type: None,
},
PaymentMethodUpdate::StatusUpdate { status } => Self {
metadata: None,
@@ -253,12 +265,16 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
locker_id: None,
payment_method: None,
connector_mandate_details: None,
+ payment_method_issuer: None,
+ payment_method_type: None,
},
PaymentMethodUpdate::AdditionalDataUpdate {
payment_method_data,
status,
locker_id,
payment_method,
+ payment_method_type,
+ payment_method_issuer,
} => Self {
metadata: None,
payment_method_data,
@@ -268,6 +284,8 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
locker_id,
payment_method,
connector_mandate_details: None,
+ payment_method_issuer,
+ payment_method_type,
},
PaymentMethodUpdate::ConnectorMandateDetailsUpdate {
connector_mandate_details,
@@ -280,6 +298,8 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
payment_method: None,
connector_mandate_details,
network_transaction_id: None,
+ payment_method_issuer: None,
+ payment_method_type: None,
},
}
}
diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rs
index 537f6666c5d..423f8e03d23 100644
--- a/crates/router/src/configs/secrets_transformers.rs
+++ b/crates/router/src/configs/secrets_transformers.rs
@@ -365,5 +365,6 @@ pub(crate) async fn fetch_raw_secrets(
connector_onboarding,
cors: conf.cors,
unmasked_headers: conf.unmasked_headers,
+ saved_payment_methods: conf.saved_payment_methods,
}
}
diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs
index 01b05c60bd9..12ce9c39d6f 100644
--- a/crates/router/src/configs/settings.rs
+++ b/crates/router/src/configs/settings.rs
@@ -119,6 +119,7 @@ pub struct Settings<S: SecretState> {
#[cfg(feature = "olap")]
pub connector_onboarding: SecretStateContainer<ConnectorOnboarding, S>,
pub unmasked_headers: UnmaskedHeaders,
+ pub saved_payment_methods: EligiblePaymentMethods,
}
#[derive(Debug, Deserialize, Clone, Default)]
@@ -165,6 +166,11 @@ pub struct PaymentMethodAuth {
pub pm_auth_key: Secret<String>,
}
+#[derive(Debug, Deserialize, Clone, Default)]
+pub struct EligiblePaymentMethods {
+ pub sdk_eligible_payment_methods: HashSet<String>,
+}
+
#[derive(Debug, Deserialize, Clone, Default)]
pub struct DefaultExchangeRates {
pub base_currency: String,
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index 27d126bce90..d3f6aeea24b 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -441,6 +441,8 @@ pub async fn add_payment_method_data(
status: Some(enums::PaymentMethodStatus::Active),
locker_id: Some(locker_id),
payment_method: req.payment_method,
+ payment_method_issuer: req.payment_method_issuer,
+ payment_method_type: req.payment_method_type,
};
db.update_payment_method(
@@ -555,7 +557,7 @@ pub async fn add_payment_method(
match duplication_check {
Some(duplication_check) => match duplication_check {
payment_methods::DataDuplicationCheck::Duplicated => {
- get_or_insert_payment_method(
+ let existing_pm = get_or_insert_payment_method(
db,
req.clone(),
&mut resp,
@@ -564,6 +566,8 @@ pub async fn add_payment_method(
key_store,
)
.await?;
+
+ resp.client_secret = existing_pm.client_secret;
}
payment_methods::DataDuplicationCheck::MetaDataChanged => {
if let Some(card) = req.card.clone() {
@@ -577,6 +581,8 @@ pub async fn add_payment_method(
)
.await?;
+ let client_secret = existing_pm.client_secret.clone();
+
delete_card_from_locker(
&state,
&customer_id,
@@ -653,6 +659,8 @@ pub async fn add_payment_method(
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to add payment method in db")?;
+
+ resp.client_secret = client_secret;
}
}
},
@@ -667,7 +675,7 @@ pub async fn add_payment_method(
None
};
resp.payment_method_id = generate_id(consts::ID_LENGTH, "pm");
- insert_payment_method(
+ let pm = insert_payment_method(
db,
&resp,
req,
@@ -682,6 +690,8 @@ pub async fn add_payment_method(
merchant_account.storage_scheme,
)
.await?;
+
+ resp.client_secret = pm.client_secret;
}
}
@@ -744,6 +754,18 @@ pub async fn update_customer_payment_method(
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
+ if pm.status == enums::PaymentMethodStatus::AwaitingData {
+ return Err(report!(errors::ApiErrorResponse::NotSupported {
+ message: "Payment method is awaiting data so it cannot be updated".into()
+ }));
+ }
+
+ if pm.payment_method_data.is_none() {
+ return Err(report!(errors::ApiErrorResponse::GenericNotFoundError {
+ message: "payment_method_data not found".to_string()
+ }));
+ }
+
// Fetch the existing payment method data from db
let existing_card_data = decrypt::<serde_json::Value, masking::WithType>(
pm.payment_method_data.clone(),
@@ -812,7 +834,7 @@ pub async fn update_customer_payment_method(
wallet: req.wallet,
metadata: req.metadata,
customer_id: Some(pm.customer_id.clone()),
- client_secret: None,
+ client_secret: pm.client_secret.clone(),
payment_method_data: None,
card_network: req
.card_network
@@ -901,7 +923,7 @@ pub async fn update_customer_payment_method(
installment_payment_enabled: false,
payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]),
last_used_at: Some(common_utils::date_time::now()),
- client_secret: None,
+ client_secret: pm.client_secret.clone(),
}
};
@@ -1691,12 +1713,21 @@ pub async fn list_payment_methods(
let db = &*state.store;
let pm_config_mapping = &state.conf.pm_filters;
- let payment_intent = helpers::verify_payment_intent_time_and_client_secret(
- db,
- &merchant_account,
- req.client_secret.clone(),
- )
- .await?;
+ let payment_intent = if let Some(cs) = &req.client_secret {
+ if cs.starts_with("pm_") {
+ validate_payment_method_and_client_secret(cs, db, &merchant_account).await?;
+ None
+ } else {
+ helpers::verify_payment_intent_time_and_client_secret(
+ db,
+ &merchant_account,
+ req.client_secret.clone(),
+ )
+ .await?
+ }
+ } else {
+ None
+ };
let shipping_address = payment_intent
.as_ref()
@@ -1839,6 +1870,7 @@ pub async fn list_payment_methods(
pm_config_mapping,
&state.conf.mandates.supported_payment_methods,
&state.conf.mandates.update_mandate_supported,
+ &state.conf.saved_payment_methods,
)
.await?;
}
@@ -2535,6 +2567,34 @@ pub async fn list_payment_methods(
))
}
+async fn validate_payment_method_and_client_secret(
+ cs: &String,
+ db: &dyn db::StorageInterface,
+ merchant_account: &domain::MerchantAccount,
+) -> Result<(), error_stack::Report<errors::ApiErrorResponse>> {
+ let pm_vec = cs.split("_secret").collect::<Vec<&str>>();
+ let pm_id = pm_vec
+ .first()
+ .ok_or(errors::ApiErrorResponse::MissingRequiredField {
+ field_name: "client_secret",
+ })?;
+
+ let payment_method = db
+ .find_payment_method(pm_id, merchant_account.storage_scheme)
+ .await
+ .change_context(errors::ApiErrorResponse::PaymentMethodNotFound)
+ .attach_printable("Unable to find payment method")?;
+
+ let client_secret_expired =
+ authenticate_pm_client_secret_and_check_expiry(cs, &payment_method)?;
+ if client_secret_expired {
+ return Err::<(), error_stack::Report<errors::ApiErrorResponse>>(
+ (errors::ApiErrorResponse::ClientSecretExpired).into(),
+ );
+ }
+ Ok(())
+}
+
pub async fn call_surcharge_decision_management(
state: routes::AppState,
merchant_account: &domain::MerchantAccount,
@@ -2644,6 +2704,7 @@ pub async fn filter_payment_methods(
config: &settings::ConnectorFilters,
supported_payment_methods_for_mandate: &settings::SupportedPaymentMethodsForMandate,
supported_payment_methods_for_update_mandate: &settings::SupportedPaymentMethodsForMandate,
+ saved_payment_methods: &settings::EligiblePaymentMethods,
) -> errors::CustomResult<(), errors::ApiErrorResponse> {
for payment_method in payment_methods.into_iter() {
let parse_result = serde_json::from_value::<PaymentMethodsEnabled>(payment_method);
@@ -2761,6 +2822,20 @@ pub async fn filter_payment_methods(
})
.unwrap_or(true);
+ let filter9 = req
+ .client_secret
+ .as_ref()
+ .map(|cs| {
+ if cs.starts_with("pm_") {
+ saved_payment_methods
+ .sdk_eligible_payment_methods
+ .contains(payment_method.to_string().as_str())
+ } else {
+ true
+ }
+ })
+ .unwrap_or(true);
+
let connector = connector.clone();
let response_pm_type = ResponsePaymentMethodIntermediate::new(
@@ -2777,6 +2852,7 @@ pub async fn filter_payment_methods(
&& filter6
&& filter7
&& filter8
+ && filter9
{
resp.push(response_pm_type);
}
diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs
index 749508c9740..9c53642f4d7 100644
--- a/crates/router/src/core/payment_methods/transformers.rs
+++ b/crates/router/src/core/payment_methods/transformers.rs
@@ -374,7 +374,7 @@ pub fn mk_add_card_response_hs(
installment_payment_enabled: false, // #[#256]
payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]),
last_used_at: Some(common_utils::date_time::now()), // [#256]
- client_secret: None,
+ client_secret: req.client_secret,
}
}
|
2024-03-28T12:24:55Z
|
## 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 builds upon - https://github.com/juspay/hyperswitch/pull/4134
After generating a `pm client_secret`, `/ist_payment_methods` can be altered for vaulting purposes.
For saved payment methods, if `pm client_secret` is passed in merchant payment method list, the payment methods will be filtered on a config `saved_payment_methods`.
Only the payment methods listed in the config `saved_payment_methods` would be displayed as a part of "Vaulting eligible payment methods".
The customer can then select one of the listed payment_methods, after which the SDK will hit the `/save` API for vaulting it.
### 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)?
-->
1. Create a customer
```
curl --location --request POST 'http://localhost:8080/customers' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_y5XDvbHKvRI6K2dAhTgXvNgQykJiqLXeYtSysCQzPGBGz3RZoUPjPcfD1LW8teYO' \
--data-raw '{
"email": "guest@example.com",
"name": "John Doe1",
"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
```
curl --location --request POST 'http://localhost:8080/payment_methods' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_63yd7Y0i2CvRcJYKfXcIE8wAva0b5YMtKHr6oTpcnggVmWqsK0Q6CvoKB1WiXoTz' \
--data-raw '{
"customer_id": "cus_RHnmMuG8mKhICwigyUeP"
}'
```
Response -
```
{
"merchant_id": "sarthak",
"customer_id": "cus_RHnmMuG8mKhICwigyUeP",
"payment_method_id": "pm_8b24uUXEoZIBTcUIPRBD",
"payment_method": null,
"payment_method_type": null,
"card": null,
"recurring_enabled": false,
"installment_payment_enabled": false,
"payment_experience": null,
"metadata": null,
"created": null,
"last_used_at": null,
"client_secret": "pm_8b24uUXEoZIBTcUIPRBD_secret_FyFrpYRzEU0NH0zbQJXC"
}
```
3. Pass pm client secret in merchant pm list -
```
curl --location --request GET 'http://localhost:8080/account/payment_methods?client_secret=pm_8b24uUXEoZIBTcUIPRBD_secret_FyFrpYRzEU0NH0zbQJXC' \
--header 'Accept: application/json' \
--header 'api-key: pk_dev_ee1bf1a13355408da5f22cbee38ffca4'
```
Response -
<img width="1512" alt="image" src="https://github.com/juspay/hyperswitch/assets/76486416/da50f13b-9107-4c0f-8efc-24baa1e34d2e">
4. Save the payment method with client_secret
```
curl --location --request POST 'http://localhost:8080/payment_methods/pm_8b24uUXEoZIBTcUIPRBD/save' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: pk_dev_660e47ec672f43849d6b0403fcaf76ac' \
--data-raw '{
"payment_method": "card",
"client_secret": "pm_8b24uUXEoZIBTcUIPRBD_secret_FyFrpYRzEU0NH0zbQJXC",
"customer_id": "cus_RHnmMuG8mKhICwigyUeP",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "10",
"card_exp_year": "2026",
"card_holder_name": "joseph"
}
}
}'
```
Response -
```
{
"merchant_id": "sarthak",
"customer_id": "cus_RHnmMuG8mKhICwigyUeP",
"payment_method_id": "pm_DC74n7ocq8SKGvNVai0M",
"payment_method": "card",
"payment_method_type": null,
"card": {
"scheme": null,
"issuer_country": null,
"last4_digits": "4242",
"expiry_month": "10",
"expiry_year": "2026",
"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-04-03T13:02:00.926Z",
"last_used_at": "2024-04-03T13:02:00.926Z",
"client_secret": "pm_8b24uUXEoZIBTcUIPRBD_secret_FyFrpYRzEU0NH0zbQJXC"
}
```
## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
bcce8b0489aad8455748e0945127f0a7447e8fb1
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4084
|
Bug: [BUG] : payments response has `payment_method_billing` even if not passed in request.
### Bug Description
When a payment is created with `payment.billing`, in the response `payment.payment_method_data.billing` is also populated.
### Expected Behavior
`payment.pament_method_data.billing` should be empty or null.
### Actual Behavior
`payment.payment_method_data.billing` is not null, whereas it has the data of `payment.billing`
### Steps To Reproduce
- Create a payment using the below curl
```bash
curl --location 'https://integ-api.hyperswitch.io/payments' \
--header 'Content-Type: application/json' \
--header 'api-key: dev_digX9Cd2d0ONVCCt2x8B1lgLLorGkw18S2gOR9fLzMu72hQmPpM7I01ppNJJXzZ6' \
--data-raw '{
"amount": 6540,
"currency": "USD",
"confirm": false,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"amount_to_capture": 6540,
"customer_id": "cus_PAxm0MeCGM5TowgDKPc9",
"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://duck.com",
"payment_method": "card",
"setup_future_usage": "on_session",
"customer_acceptance": {
"acceptance_type": "online",
"accepted_at": "2022-09-10T10:11:12Z",
"online": {
"ip_address": "123.32.25.123",
"user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36"
}
},
"payment_method_type": "debit",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "12",
"card_exp_year": "26",
"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": "sundari",
"last_name": "sundari"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "sundari",
"last_name": "sundari"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}'
```
- The response should not have `payment.payment_method_data.billing`.
- The response should have `payment.billing`.
### Context For The Bug
_No response_
### Environment
Are you using hyperswitch hosted version? No
### 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/payments.rs b/crates/router/src/core/payments.rs
index b8a4c5dfc67..fb53e484afd 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -2122,6 +2122,7 @@ pub mod payment_address {
pub struct PaymentAddress {
shipping: Option<api::Address>,
billing: Option<api::Address>,
+ unified_payment_method_billing: Option<api::Address>,
payment_method_billing: Option<api::Address>,
}
@@ -2131,20 +2132,26 @@ pub mod payment_address {
billing: Option<api::Address>,
payment_method_billing: Option<api::Address>,
) -> Self {
- let payment_method_billing = match (payment_method_billing, billing.clone()) {
- (Some(payment_method_billing), Some(order_billing)) => Some(api::Address {
- address: payment_method_billing.address.or(order_billing.address),
- phone: payment_method_billing.phone.or(order_billing.phone),
- email: payment_method_billing.email.or(order_billing.email),
- }),
- (Some(payment_method_billing), None) => Some(payment_method_billing),
- (None, Some(order_billing)) => Some(order_billing),
- (None, None) => None,
- };
+ // Merge the billing details field from both `payment.billing` and `payment.payment_method_data.billing`
+ // The unified payment_method_billing will be used as billing address and passed to the connector module
+ // This unification is required in order to provide backwards compatibility
+ // so that if `payment.billing` is passed it should be sent to the connector module
+ let unified_payment_method_billing =
+ match (payment_method_billing.clone(), billing.clone()) {
+ (Some(payment_method_billing), Some(order_billing)) => Some(api::Address {
+ address: payment_method_billing.address.or(order_billing.address),
+ phone: payment_method_billing.phone.or(order_billing.phone),
+ email: payment_method_billing.email.or(order_billing.email),
+ }),
+ (Some(payment_method_billing), None) => Some(payment_method_billing),
+ (None, Some(order_billing)) => Some(order_billing),
+ (None, None) => None,
+ };
Self {
shipping,
billing,
+ unified_payment_method_billing,
payment_method_billing,
}
}
@@ -2154,6 +2161,10 @@ pub mod payment_address {
}
pub fn get_payment_method_billing(&self) -> Option<&api::Address> {
+ self.unified_payment_method_billing.as_ref()
+ }
+
+ pub fn get_request_payment_method_billing(&self) -> Option<&api::Address> {
self.payment_method_billing.as_ref()
}
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index 315ddd3b39b..73d780c0960 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -467,7 +467,10 @@ where
let payment_method_data_response = payment_method_data.map(|payment_method_data| {
api_models::payments::PaymentMethodDataResponseWithBilling {
payment_method_data,
- billing: payment_data.address.get_payment_method_billing().cloned(),
+ billing: payment_data
+ .address
+ .get_request_payment_method_billing()
+ .cloned(),
}
});
diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs
index 006c4503ce1..e9082299ab1 100644
--- a/crates/router/src/types/transformers.rs
+++ b/crates/router/src/types/transformers.rs
@@ -583,7 +583,7 @@ impl<'a> ForeignFrom<&'a api_types::ConfigUpdate> for storage::ConfigUpdate {
impl<'a> From<&'a domain::Address> for api_types::Address {
fn from(address: &domain::Address) -> Self {
- // If all the fields of address are none, then
+ // If all the fields of address are none, then pass the address as None
let address_details = if address.city.is_none()
&& address.line1.is_none()
&& address.line2.is_none()
@@ -608,12 +608,19 @@ impl<'a> From<&'a domain::Address> for api_types::Address {
})
};
- Self {
- address: address_details,
- phone: Some(api_types::PhoneDetails {
+ // If all the fields of phone are none, then pass the phone as None
+ let phone_details = if address.phone_number.is_none() && address.country_code.is_none() {
+ None
+ } else {
+ Some(api_types::PhoneDetails {
number: address.phone_number.clone().map(Encryptable::into_inner),
country_code: address.country_code.clone(),
- }),
+ })
+ };
+
+ Self {
+ address: address_details,
+ phone: phone_details,
email: address.email.clone().map(pii::Email::from),
}
}
diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Create payment with payment method billing/Payments - Create/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Create payment with payment method billing/Payments - Create/event.test.js
index d18cc474f87..cad157942d1 100644
--- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Create payment with payment method billing/Payments - Create/event.test.js
+++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Create payment with payment method billing/Payments - Create/event.test.js
@@ -87,3 +87,11 @@ pm.test(
.true;
},
);
+
+// Response body should not have "payment.billing"
+pm.test(
+ "[POST]::/payments - Content check if 'payment.billing' is null",
+ function () {
+ pm.expect(jsonData?.billing).to.be.null
+ },
+);
diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Create payment with payment method billing/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Create payment with payment method billing/Payments - Create/request.json
index 7a755ed4e6e..83e3a58da2e 100644
--- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Create payment with payment method billing/Payments - Create/request.json
+++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario29-Create payment with payment method billing/Payments - Create/request.json
@@ -60,19 +60,6 @@
"email": "example@juspay.in"
}
},
- "billing": {
- "address": {
- "line1": "1467",
- "line2": "Harrison Street",
- "line3": "Harrison Street",
- "city": "San Fransico",
- "state": "California",
- "zip": "94122",
- "country": "US",
- "first_name": "sundari",
- "last_name": "sundari"
- }
- },
"shipping": {
"address": {
"line1": "1467",
diff --git a/postman/collection-dir/stripe/QuickStart/Payments - Create/event.test.js b/postman/collection-dir/stripe/QuickStart/Payments - Create/event.test.js
index 3d51aaa49a8..93d36d988d4 100644
--- a/postman/collection-dir/stripe/QuickStart/Payments - Create/event.test.js
+++ b/postman/collection-dir/stripe/QuickStart/Payments - Create/event.test.js
@@ -97,3 +97,11 @@ pm.test(
.true;
},
);
+
+// Response body should not have "payment_method_data.billing"
+pm.test(
+ "[POST]::/payments - Content check if 'payment_method_data.billing' should be null",
+ function () {
+ pm.expect(jsonData?.payment_method_data?.billing).to.be.null;
+ },
+);
diff --git a/postman/collection-json/stripe.postman_collection.json b/postman/collection-json/stripe.postman_collection.json
index c3d6371fd7d..46829047bd2 100644
--- a/postman/collection-json/stripe.postman_collection.json
+++ b/postman/collection-json/stripe.postman_collection.json
@@ -2451,6 +2451,14 @@
" .true;",
" },",
");",
+ "",
+ "// Response body should not have \"payment_method_data.billing\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'payment_method_data.billing' should be null\",",
+ " function () {",
+ " pm.expect(jsonData?.payment_method_data?.billing).to.be.null;",
+ " },",
+ ");",
""
],
"type": "text/javascript"
@@ -20865,6 +20873,14 @@
" .true;",
" },",
");",
+ "",
+ "// Response body should not have \"payment.billing\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'payment.billing' is null\",",
+ " function () {",
+ " pm.expect(jsonData?.billing).to.be.null",
+ " },",
+ ");",
""
],
"type": "text/javascript"
@@ -20890,7 +20906,7 @@
"language": "json"
}
},
- "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"business_country\":\"US\",\"business_label\":\"default\",\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"bernard123\",\"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://duck.com\",\"setup_future_usage\":\"on_session\",\"payment_method\":\"card\",\"payment_method_type\":\"debit\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"01\",\"card_exp_year\":\"26\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrisoff Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"Narayan\",\"last_name\":\"Doe\"},\"email\":\"example@juspay.in\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\",\"last_name\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\",\"last_name\":\"sundari\"}},\"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\":6540,\"currency\":\"USD\",\"confirm\":true,\"business_country\":\"US\",\"business_label\":\"default\",\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"bernard123\",\"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://duck.com\",\"setup_future_usage\":\"on_session\",\"payment_method\":\"card\",\"payment_method_type\":\"debit\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"01\",\"card_exp_year\":\"26\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrisoff Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"Narayan\",\"last_name\":\"Doe\"},\"email\":\"example@juspay.in\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\",\"last_name\":\"sundari\"}},\"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",
|
2024-03-14T04:37:42Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
## Description
<!-- Describe your changes in detail -->
This PR fixes the inconsistency in payments response. More details can be found in the linked issue.
## 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)?
-->
- Added postman test cases
- Create a payment without `payment_method_billing`.
```bash
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'api-key: dev_RenK6PvquNMkUrABw8BOK9A8zbl4Zh270G1zjFDc7KMGkc5XJY5mgAnv6iDbnKIn' \
--data-raw '{
"amount": 6540,
"currency": "USD",
"confirm": true,
"payment_method": "card",
"payment_method_data": {
"card": {
"card_number": "4000000000000101",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrisoff Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "Narayan",
"last_name": "Doe"
},
"email": "example@juspay.in"
}
}'
```
- Response
```json
{
"payment_id": "pay_ZjoHfCqtenTCCd0fBUEc",
"merchant_id": "merchant_1710395888",
"status": "succeeded",
"amount": 6540,
"net_amount": 6540,
"amount_capturable": 0,
"amount_received": 6540,
"connector": "stripe",
"client_secret": "pay_ZjoHfCqtenTCCd0fBUEc_secret_6SzPF2EQfTFVpedXJaqE",
"created": "2024-03-15T09:37:12.679Z",
"currency": "USD",
"customer_id": 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": "0101",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "400000",
"card_extended_bin": "40000000",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe"
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrisoff Street",
"zip": "94122",
"state": "California",
"first_name": "Narayan",
"last_name": "Doe"
},
"phone": null,
"email": "example@juspay.in"
},
"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": null,
"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": "pi_3OuXCPD5R7gDAGff05AoM0mg",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pi_3OuXCPD5R7gDAGff05AoM0mg",
"payment_link": null,
"profile_id": "pro_uMo0FiDFjCIAtLfdHK1J",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_NYBLuh0YMth90TWWn3k5",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-03-15T09:52:12.679Z",
"fingerprint": null,
"payment_method_id": null,
"payment_method_status": null
}
```
- Create a payment with `payment_method_billing`.
```bash
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'api-key: dev_RenK6PvquNMkUrABw8BOK9A8zbl4Zh270G1zjFDc7KMGkc5XJY5mgAnv6iDbnKIn' \
--data-raw '{
"amount": 6540,
"currency": "USD",
"confirm": true,
"payment_method": "card",
"payment_method_data": {
"card": {
"card_number": "4000000000000101",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrisoff Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "Narayan",
"last_name": "Doe"
},
"email": "example@juspay.in"
}
}
}'
```
- Response
```json
{
"payment_id": "pay_4T2Q81rgIeAO7gOxpIQM",
"merchant_id": "merchant_1710395888",
"status": "succeeded",
"amount": 6540,
"net_amount": 6540,
"amount_capturable": 0,
"amount_received": 6540,
"connector": "stripe",
"client_secret": "pay_4T2Q81rgIeAO7gOxpIQM_secret_GXFlAK6whO0llT5nLQaf",
"created": "2024-03-15T09:39:37.428Z",
"currency": "USD",
"customer_id": 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": "0101",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "400000",
"card_extended_bin": "40000000",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe"
},
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrisoff Street",
"zip": "94122",
"state": "California",
"first_name": "Narayan",
"last_name": "Doe"
},
"phone": null,
"email": "example@juspay.in"
}
},
"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": null,
"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": "pi_3OuXEkD5R7gDAGff1EBDw2dH",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pi_3OuXEkD5R7gDAGff1EBDw2dH",
"payment_link": null,
"profile_id": "pro_uMo0FiDFjCIAtLfdHK1J",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_NYBLuh0YMth90TWWn3k5",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-03-15T09:54:37.428Z",
"fingerprint": null,
"payment_method_id": null,
"payment_method_status": null
}
```
- Create a payment with both billing.
```bash
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'api-key: dev_RenK6PvquNMkUrABw8BOK9A8zbl4Zh270G1zjFDc7KMGkc5XJY5mgAnv6iDbnKIn' \
--data-raw '{
"amount": 6540,
"currency": "USD",
"confirm": true,
"payment_method": "card",
"payment_method_data": {
"card": {
"card_number": "4000000000000101",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
},
"billing": {
"address": {
"state": "Karnataka",
"zip": "94122",
"country": "IN",
"first_name": "Narayan",
"last_name": "Doe"
},
"email": "example@juspay.in"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrisoff Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "Chaser",
"last_name": "Dough"
},
"email": "example@juspay.in"
}
}'
```
- Response ( both billing should be different )
```json
{
"payment_id": "pay_nsM4uQjQ3S9QbrjBDhzj",
"merchant_id": "merchant_1710395888",
"status": "succeeded",
"amount": 6540,
"net_amount": 6540,
"amount_capturable": 0,
"amount_received": 6540,
"connector": "stripe",
"client_secret": "pay_nsM4uQjQ3S9QbrjBDhzj_secret_iV3hnUtQwC95aWDhEcV0",
"created": "2024-03-15T09:40:56.482Z",
"currency": "USD",
"customer_id": 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": "0101",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "400000",
"card_extended_bin": "40000000",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe"
},
"billing": {
"address": {
"city": null,
"country": "IN",
"line1": null,
"line2": null,
"line3": null,
"zip": "94122",
"state": "Karnataka",
"first_name": "Narayan",
"last_name": "Doe"
},
"phone": null,
"email": "example@juspay.in"
}
},
"payment_token": null,
"shipping": null,
"billing": {
"address": {
"city": "San Fransico",
"country": "US",
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrisoff Street",
"zip": "94122",
"state": "California",
"first_name": "Chaser",
"last_name": "Dough"
},
"phone": null,
"email": "example@juspay.in"
},
"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": null,
"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": "pi_3OuXG1D5R7gDAGff0sH2G6LI",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "pi_3OuXG1D5R7gDAGff0sH2G6LI",
"payment_link": null,
"profile_id": "pro_uMo0FiDFjCIAtLfdHK1J",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_NYBLuh0YMth90TWWn3k5",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"external_3ds_authentication_attempted": false,
"expires_on": "2024-03-15T09:55:56.482Z",
"fingerprint": null,
"payment_method_id": null,
"payment_method_status": 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
|
74345212ed3052c54323ae143cd89a4b03b23d15
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4079
|
Bug: [FEATURE] [AUTHORIZEDOTNET] Add apple pay manual flow to dashboard
### Feature Description
Apple pay manual flow needs to be added for authorizedotnet in the following dashboards:
1. Integ
2. Sandbox
3. Production
### Possible Implementation
Apple pay manual flow needs to be added for authorizedotnet in the following dashboards by doing wasm config changes:
1. Integ
2. Sandbox
3. Production
### 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 58e54c36220..11025de310a 100644
--- a/crates/connector_configs/toml/development.toml
+++ b/crates/connector_configs/toml/development.toml
@@ -334,6 +334,8 @@ merchant_secret="Source verification key"
payment_method_type = "CartesBancaires"
[[authorizedotnet.debit]]
payment_method_type = "UnionPay"
+[[authorizedotnet.wallet]]
+ payment_method_type = "apple_pay"
[[authorizedotnet.wallet]]
payment_method_type = "google_pay"
[[authorizedotnet.wallet]]
@@ -345,6 +347,17 @@ key1="Transaction Key"
merchant_name="Google Pay Merchant Name"
gateway_merchant_id="Google Pay Merchant Key"
merchant_id="Google Pay Merchant ID"
+[authorizedotnet.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"
+[authorizedotnet.metadata.apple_pay.payment_request_data]
+supported_networks=["visa","masterCard","amex","discover"]
+merchant_capabilities=["supports3DS"]
+label="apple"
[authorizedotnet.connector_webhook_details]
merchant_secret="Source verification key"
diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml
index 41facc9732f..079ead7e4ce 100644
--- a/crates/connector_configs/toml/production.toml
+++ b/crates/connector_configs/toml/production.toml
@@ -227,6 +227,8 @@ merchant_secret="Source verification key"
payment_method_type = "CartesBancaires"
[[authorizedotnet.debit]]
payment_method_type = "UnionPay"
+[[authorizedotnet.wallet]]
+ payment_method_type = "apple_pay"
[[authorizedotnet.wallet]]
payment_method_type = "google_pay"
[[authorizedotnet.wallet]]
@@ -239,6 +241,17 @@ key1="Transaction Key"
merchant_name="Google Pay Merchant Name"
gateway_merchant_id="Google Pay Merchant Key"
merchant_id="Google Pay Merchant ID"
+[authorizedotnet.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"
+[authorizedotnet.metadata.apple_pay.payment_request_data]
+supported_networks=["visa","masterCard","amex","discover"]
+merchant_capabilities=["supports3DS"]
+label="apple"
[authorizedotnet.connector_webhook_details]
merchant_secret="Source verification key"
diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml
index c93acee4736..6913885d3fd 100644
--- a/crates/connector_configs/toml/sandbox.toml
+++ b/crates/connector_configs/toml/sandbox.toml
@@ -334,6 +334,8 @@ merchant_secret="Source verification key"
payment_method_type = "CartesBancaires"
[[authorizedotnet.debit]]
payment_method_type = "UnionPay"
+[[authorizedotnet.wallet]]
+ payment_method_type = "apple_pay"
[[authorizedotnet.wallet]]
payment_method_type = "google_pay"
[[authorizedotnet.wallet]]
@@ -345,6 +347,17 @@ key1="Transaction Key"
merchant_name="Google Pay Merchant Name"
gateway_merchant_id="Google Pay Merchant Key"
merchant_id="Google Pay Merchant ID"
+[authorizedotnet.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"
+[authorizedotnet.metadata.apple_pay.payment_request_data]
+supported_networks=["visa","masterCard","amex","discover"]
+merchant_capabilities=["supports3DS"]
+label="apple"
[authorizedotnet.connector_webhook_details]
merchant_secret="Source verification key"
|
2024-03-13T14:24: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 -->
Apple pay manual flow is added for authorizedotnet in the following dashboards:
1. Integ
2. Sandbox
3. Production
### 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/4079
## 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)?
-->
Only Dashboard WASM Changes
## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
a21d6d5e16730e0d12ea924066b4592c76f26bfd
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4083
|
Bug: [FEATURE] : [Cybersource] Add Card holder name in dynamic field
### Feature Description
Add Card holder name as required field in dynamic field
### Possible Implementation
Add Card holder name as required field in dynamic field in `default.rs`
### 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/configs/defaults.rs b/crates/router/src/configs/defaults.rs
index 5c2d62b40b8..f9d98647d1b 100644
--- a/crates/router/src/configs/defaults.rs
+++ b/crates/router/src/configs/defaults.rs
@@ -757,7 +757,8 @@ impl Default for super::settings::RequiredFields {
enums::Connector::Cybersource,
RequiredFieldFinal {
mandate: HashMap::new(),
- non_mandate: HashMap::from(
+ non_mandate: HashMap::new(),
+ common:HashMap::from(
[
(
"payment_method_data.card.card_number".to_string(),
@@ -795,6 +796,15 @@ impl Default for super::settings::RequiredFields {
value: None,
}
),
+ (
+ "payment_method_data.card.card_holder_name".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_holder_name".to_string(),
+ display_name: "card_holder_name".to_string(),
+ field_type: enums::FieldType::UserFullName,
+ value: None,
+ }
+ ),
(
"email".to_string(),
RequiredFieldInfo {
@@ -873,7 +883,6 @@ impl Default for super::settings::RequiredFields {
)
]
),
- common:HashMap::new(),
}
),
(
@@ -2853,6 +2862,15 @@ impl Default for super::settings::RequiredFields {
value: None,
}
),
+ (
+ "payment_method_data.card.card_holder_name".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_holder_name".to_string(),
+ display_name: "card_holder_name".to_string(),
+ field_type: enums::FieldType::UserFullName,
+ value: None,
+ }
+ ),
(
"email".to_string(),
RequiredFieldInfo {
@@ -4783,7 +4801,8 @@ impl Default for super::settings::RequiredFields {
field_type: enums::FieldType::UserBank,
value: None,
}
- )
+ ),
+
]),
}
),
|
2024-03-13T19:33:13Z
|
## 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 -->
add card holder name as a required field in dynamic fields for cyber source
### 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).
-->
#4083
## 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 payment for Cybersource with confirm false
```
curl --location 'http://localhost:8080/payments' \
--header 'Accept: application/json' \
--header 'Content-Type: application/json' \
--header 'api-key: dev_NEqxtA08zn0qi3szJqYNmFXpQQt41BfwDpOE1sVucX37yJUN7jpR6QkmrlJCuWf5' \
--data-raw '{
"amount": 9040,
"currency": "USD",
"confirm": false,
"capture_method": "automatic",
"customer_id": "shanks5",
"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",
"billing": {
"address": {
"city": "SanFransico",
"country": "AE",
"line1": "1562",
"line2": "HarrisonStreet",
"line3": "HarrisonStreet",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"setup_future_usage": "off_session",
"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"
}
]
}'
```
- Retrieve payment method list for the merchant, card holder name should be present as required field
<img width="1129" alt="Screenshot 2024-03-14 at 1 02 47 AM" src="https://github.com/juspay/hyperswitch/assets/55536657/78879e1d-4f5d-4aa4-bb51-13020bee4e6e">
## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
74345212ed3052c54323ae143cd89a4b03b23d15
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4074
|
Bug: [BUG] `requires_cvv` being sent as `true` in customer payment methods list for off-session payments
### Bug Description
When doing a customer payment methods list for an off-session payment, `requires_cvv` is received as `true`.
### Expected Behavior
For off-session payments, `requires_cvv` should be false.
### Actual Behavior
It's being sent as true by default
### Steps To Reproduce
1. Set up an MIT with any connector
2. Create an off-session payment
3. Do a customer payment methods list call
### 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/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index 847950d4f45..4c38e41e9bb 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -2736,6 +2736,16 @@ pub async fn list_customer_payment_method(
}
};
+ let off_session_payment_flag = payment_intent
+ .as_ref()
+ .map(|pi| {
+ matches!(
+ pi.setup_future_usage,
+ Some(common_enums::FutureUsage::OffSession)
+ )
+ })
+ .unwrap_or(false);
+
let customer = db
.find_customer_by_customer_id_merchant_id(
customer_id,
@@ -2872,7 +2882,8 @@ pub async fn list_customer_payment_method(
bank_transfer: pmd,
bank: bank_details,
surcharge_details: None,
- requires_cvv,
+ 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),
|
2024-03-13T11:47: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 -->
This PR updates the logic to decide the `requires_cvv` parameter in the customer payment methods list api to also depend on whether the payment is an off-session payment.
### 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).
-->
For off-session payments, the cvv is not required, so it should not be mandatory for off-session payments.
## 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)?
-->
List Customer Payment Methods for normal payment (requires_cvv = true):
<img width="546" alt="image" src="https://github.com/juspay/hyperswitch/assets/47862918/8e72d476-89a8-4e2b-ae11-b9a4074065be">
List Customer Payment Methods for off-session payment (requires_cvv = false):
<img width="546" alt="image" src="https://github.com/juspay/hyperswitch/assets/47862918/649bc7b9-5561-42aa-9564-119adc7d143d">
## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
d82960c1cca5ae43d1a51f8fff6f7b6b9e016c2b
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4072
|
Bug: add dispute events to global search indexes
add dispute events to global search indexes
|
diff --git a/config/config.example.toml b/config/config.example.toml
index daf554f00ad..b5344882913 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -599,3 +599,4 @@ region = "eu-central-1"
payment_attempts = "hyperswitch-payment-attempt-events"
payment_intents = "hyperswitch-payment-intent-events"
refunds = "hyperswitch-refund-events"
+disputes = "hyperswitch-dispute-events"
diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml
index cfe696e42c0..3c971d69f8a 100644
--- a/config/deployments/env_specific.toml
+++ b/config/deployments/env_specific.toml
@@ -213,6 +213,7 @@ region = "eu-central-1"
payment_attempts = "hyperswitch-payment-attempt-events"
payment_intents = "hyperswitch-payment-intent-events"
refunds = "hyperswitch-refund-events"
+disputes = "hyperswitch-dispute-events"
# This section provides some secret values.
[secrets]
diff --git a/config/development.toml b/config/development.toml
index a7abec7fb74..0878caf3e63 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -596,3 +596,4 @@ region = "eu-central-1"
payment_attempts = "hyperswitch-payment-attempt-events"
payment_intents = "hyperswitch-payment-intent-events"
refunds = "hyperswitch-refund-events"
+disputes = "hyperswitch-dispute-events"
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index 4d1731b53ff..6a01c14fdb2 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -454,4 +454,5 @@ region = "eu-central-1"
[opensearch.indexes]
payment_attempts = "hyperswitch-payment-attempt-events"
payment_intents = "hyperswitch-payment-intent-events"
-refunds = "hyperswitch-refund-events"
\ No newline at end of file
+refunds = "hyperswitch-refund-events"
+disputes = "hyperswitch-dispute-events"
diff --git a/crates/analytics/src/lib.rs b/crates/analytics/src/lib.rs
index 68ca51a0df0..a325442047e 100644
--- a/crates/analytics/src/lib.rs
+++ b/crates/analytics/src/lib.rs
@@ -679,6 +679,7 @@ pub struct OpensearchIndexes {
pub payment_attempts: String,
pub payment_intents: String,
pub refunds: String,
+ pub disputes: String,
}
#[derive(Clone, Debug, serde::Deserialize)]
@@ -700,6 +701,7 @@ impl Default for OpensearchConfig {
payment_attempts: "hyperswitch-payment-attempt-events".to_string(),
payment_intents: "hyperswitch-payment-intent-events".to_string(),
refunds: "hyperswitch-refund-events".to_string(),
+ disputes: "hyperswitch-dispute-events".to_string(),
},
}
}
diff --git a/crates/analytics/src/search.rs b/crates/analytics/src/search.rs
index 8637c9d1105..d9b8433ba63 100644
--- a/crates/analytics/src/search.rs
+++ b/crates/analytics/src/search.rs
@@ -34,6 +34,7 @@ pub fn search_index_to_opensearch_index(index: SearchIndex, config: &OpensearchI
SearchIndex::PaymentAttempts => config.payment_attempts.clone(),
SearchIndex::PaymentIntents => config.payment_intents.clone(),
SearchIndex::Refunds => config.refunds.clone(),
+ SearchIndex::Disputes => config.disputes.clone(),
}
}
diff --git a/crates/api_models/src/analytics/search.rs b/crates/api_models/src/analytics/search.rs
index 07223c90660..3a5b3c307e6 100644
--- a/crates/api_models/src/analytics/search.rs
+++ b/crates/api_models/src/analytics/search.rs
@@ -36,6 +36,7 @@ pub enum SearchIndex {
PaymentAttempts,
PaymentIntents,
Refunds,
+ Disputes,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
|
2024-03-13T10:15:27Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [x] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
Search APIs for dashboard global search enhancement - adding dispute events index
### 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
add dispute events index to global-search
## How did you test it?
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`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
d82960c1cca5ae43d1a51f8fff6f7b6b9e016c2b
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4069
|
Bug: [BUG] Give higher precedence to connector mandate id over network txn id for mandates
### Bug Description
Recurring mandate payments with Adyen fail with a payment method not found error.
### Expected Behavior
When doing recurring mandate payments with Adyen, the core should make the payment with the connector mandate id stored in the mandate object in DB.
### Actual Behavior
Currently, if a mandate has both an associated network transaction id and connector mandate id, the core picks the network transaction id for recurring mandate transactions. This is the case for Adyen.
### Steps To Reproduce
1. Create a Merchant Account and an Adyen MCA
2. Create a mandate payment
3. Try to do a recurring mandate payment
### Context For The Bug
_No response_
### Environment
Are you using hyperswitch hosted version? No
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/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs
index 2fd559680ea..fb80c0a1c48 100644
--- a/crates/router/src/connector/cybersource/transformers.rs
+++ b/crates/router/src/connector/cybersource/transformers.rs
@@ -508,8 +508,15 @@ impl
.map_or(false, |future_usage| {
matches!(future_usage, FutureUsage::OffSession)
})
- && item.router_data.request.customer_acceptance.is_some()
- {
+ && (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(vec![CybersourceActionsList::TokenCreate]),
Some(vec![CybersourceActionsTokenType::PaymentInstrument]),
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index 6e185ea66d8..5efbee0bc6b 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -301,14 +301,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
mandate_obj.network_transaction_id,
mandate_obj.connector_mandate_ids,
) {
- (Some(network_tx_id), _) => Ok(api_models::payments::MandateIds {
- mandate_id: Some(mandate_obj.mandate_id),
- mandate_reference_id: Some(
- api_models::payments::MandateReferenceId::NetworkMandateId(
- network_tx_id,
- ),
- ),
- }),
(_, Some(connector_mandate_id)) => connector_mandate_id
.parse_value("ConnectorMandateId")
.change_context(errors::ApiErrorResponse::MandateNotFound)
@@ -324,6 +316,14 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
))
}
}),
+ (Some(network_tx_id), _) => Ok(api_models::payments::MandateIds {
+ mandate_id: Some(mandate_obj.mandate_id),
+ mandate_reference_id: Some(
+ api_models::payments::MandateReferenceId::NetworkMandateId(
+ network_tx_id,
+ ),
+ ),
+ }),
(_, _) => Ok(api_models::payments::MandateIds {
mandate_id: Some(mandate_obj.mandate_id),
mandate_reference_id: None,
|
2024-03-13T10:30:25Z
|
## 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 in the core, for a recurring mandate payment, if the mandate has both a network transaction ID and a connector mandate ID associated with it, the core picks the network transaction ID for making the recurring payment. This causes mandate payments to fail since we don't yet have support for making recurring mandate payments using a network transaction ID.
### 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)?
-->
Recurring Mandate payment with Adyen
Initial Mandate Payment:
<img width="546" alt="image" src="https://github.com/juspay/hyperswitch/assets/47862918/c9701cef-ca32-4428-bc6a-b91feb026e7c">
Recurring Mandate payment (Succeeding):
<img width="546" alt="image" src="https://github.com/juspay/hyperswitch/assets/47862918/6b75a147-7074-4ab0-b339-a11c66e64f68">
## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
fad23ad032971497b07035c530397539413b7653
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4067
|
Bug: [BUG] WASM build is failing
### Bug Description
WASM build fails when I run `make euclid-wasm`
### Expected Behavior
Build should be completed successfully
### Actual Behavior
Build Fails
### Steps To Reproduce
Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant.
Run `make euclid-wasm`
### 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/cards/src/validate.rs b/crates/cards/src/validate.rs
index 14d4c6e4c12..08ad127047c 100644
--- a/crates/cards/src/validate.rs
+++ b/crates/cards/src/validate.rs
@@ -2,7 +2,7 @@ use std::{fmt, ops::Deref, str::FromStr};
use masking::{PeekInterface, Strategy, StrongSecret, WithType};
#[cfg(not(target_arch = "wasm32"))]
-use router_env::logger;
+use router_env::{logger, which as router_env_which, Env};
use serde::{Deserialize, Deserializer, Serialize};
use thiserror::Error;
@@ -52,14 +52,16 @@ impl FromStr for CardNumber {
fn from_str(s: &str) -> Result<Self, Self::Err> {
// Valid test cards for threedsecureio
- let valid_test_cards = match router_env::which() {
- router_env::Env::Development | router_env::Env::Sandbox => vec![
- "4000100511112003",
- "6000100611111203",
- "3000100811111072",
- "9000100111111111",
- ],
- router_env::Env::Production => vec![],
+ let valid_test_cards = vec![
+ "4000100511112003",
+ "6000100611111203",
+ "3000100811111072",
+ "9000100111111111",
+ ];
+ #[cfg(not(target_arch = "wasm32"))]
+ let valid_test_cards = match router_env_which() {
+ 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();
|
2024-03-13T09:43:15Z
|
## 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 -->
Fixed `FromStr` implementation on `CardNumber` to work with wasm related feature configs.
### 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)?
-->
Run `make euclid-wasm` to verify if Wasm build was successful.
<img width="1180" alt="Screenshot 2024-03-13 at 3 12 07 PM" src="https://github.com/juspay/hyperswitch/assets/61539176/480b4373-36ba-401a-a18c-849541c524d7">
## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
d82960c1cca5ae43d1a51f8fff6f7b6b9e016c2b
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4059
|
Bug: [REFACTOR]: [Fiserv] Remove Default Case Handling
### :memo: Feature Description
- We utilize match statements to make pivotal decisions, such as generating requests based on the payment method type and managing responses received from the connector.
- These conditions generally go hand in hand with enum variants.
- Default case is used because a match statement needs to be exhaustive i.e. every variant needs to be covered.
- So, if all the explicit cases are handled then default is used to handle the rest.
- Each connector have these match statements but many of them don’t provide reference to each variant in their default case, rather a `_` is put to handle all the other cases.
- This approach carries a risk because developers may inadvertently overlook the need for explicit handling of the new cases.
### :hammer: Possible Implementation
- Instead of relying on a default match case `_`, developers should handle each and every variant explicitly.
- By doing so, if there are any changes in the future, they can readily assess the impact of their modifications simply by compiling the code.
- In order to manage payment methods that are not implemented by Hyperswitch or yet to be implemented, the connector transformers file should make use of the NotImplemented ConnectorError enum variant.
- By doing so, we will throw same error message for all the Connector Implementation
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1955
:bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/fiserv/transformer.rs`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
|
diff --git a/crates/router/src/connector/fiserv/transformers.rs b/crates/router/src/connector/fiserv/transformers.rs
index 2dedb92d1dd..8945f7814b2 100644
--- a/crates/router/src/connector/fiserv/transformers.rs
+++ b/crates/router/src/connector/fiserv/transformers.rs
@@ -386,7 +386,7 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, FiservSyncResponse, T, types::Pa
) -> Result<Self, Self::Error> {
let gateway_resp = match item.response.sync_responses.first() {
Some(gateway_response) => gateway_response,
- _ => Err(errors::ConnectorError::ResponseHandlingFailed)?,
+ None => Err(errors::ConnectorError::ResponseHandlingFailed)?,
};
Ok(Self {
|
2024-05-26T16:39:04Z
|
## 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 closes #4059
removes the default case handling in `hyperswitch/crates/router/src/connector/fiserv/transformer.rs`.
### 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`
-->
`hyperswitch/crates/router/src/connector/fiserv/transformer.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).
-->
## How did you test it?
No testing required
## 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
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4054
|
Bug: [REFACTOR]: [Bambora] Remove Default Case Handling
### :memo: Feature Description
- We utilize match statements to make pivotal decisions, such as generating requests based on the payment method type and managing responses received from the connector.
- These conditions generally go hand in hand with enum variants.
- Default case is used because a match statement needs to be exhaustive i.e. every variant needs to be covered.
- So, if all the explicit cases are handled then default is used to handle the rest.
- Each connector have these match statements but many of them don’t provide reference to each variant in their default case, rather a `_` is put to handle all the other cases.
- This approach carries a risk because developers may inadvertently overlook the need for explicit handling of the new cases.
### :hammer: Possible Implementation
- Instead of relying on a default match case `_`, developers should handle each and every variant explicitly.
- By doing so, if there are any changes in the future, they can readily assess the impact of their modifications simply by compiling the code.
- In order to manage payment methods that are not implemented by Hyperswitch or yet to be implemented, the connector transformers file should make use of the NotImplemented ConnectorError enum variant.
- By doing so, we will throw same error message for all the Connector Implementation
- You can check this PR for further reference https://github.com/juspay/hyperswitch/pull/1955
:bookmark: Note: All the changes needed should be contained within `hyperswitch/crates/router/src/connector/bambora/transformer.rs`
### :package: Have you spent some time checking if this feature request has been raised before?
- [X] I checked and didn't find a similar issue
### :package: Have you read the Contributing Guidelines?
- [X] I have read the [Contributing Guidelines](https://github.com/juspay/hyperswitch/blob/main/docs/CONTRIBUTING.md)
### :sparkles: Are you willing to submit a PR?
|
diff --git a/crates/router/src/connector/bambora/transformers.rs b/crates/router/src/connector/bambora/transformers.rs
index 61ed8bd1ee4..a4c377cf9f9 100644
--- a/crates/router/src/connector/bambora/transformers.rs
+++ b/crates/router/src/connector/bambora/transformers.rs
@@ -6,7 +6,7 @@ use serde::{Deserialize, Deserializer, Serialize};
use crate::{
connector::utils::{
- AddressDetailsData, BrowserInformationData, CardData as OtherCardData,
+ self, AddressDetailsData, BrowserInformationData, CardData as OtherCardData,
PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData,
PaymentsSyncRequestData, RouterData,
},
@@ -185,7 +185,10 @@ impl TryFrom<BamboraRouterData<&types::PaymentsAuthorizeRouterData>> for Bambora
| domain::PaymentMethodData::Voucher(_)
| domain::PaymentMethodData::GiftCard(_)
| domain::PaymentMethodData::CardToken(_) => {
- Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into())
+ Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("bambora"),
+ )
+ .into())
}
}
}
|
2024-04-28T17:42:42Z
|
## 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 -->
As described in #4054, this pull request removes the default case handling in `crates/router/src/connector/bambora/transformers.rs`, handling each case explicitly.
### 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 #4054
## 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
|
a0f11d79add17e0bc19d8677c90f8a35d6c99c97
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4053
|
Bug: [REFACTOR] Enable country currency filter for cards
### Feature Description
The functionality to process payments for specific countries and currencies is required for certain connectors. This feature should be implemented based on the connector configurations for cards.
### Possible Implementation
The configuration filter for country currency on cards must be activated.
### 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/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index 847950d4f45..765eac93f59 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -2356,15 +2356,27 @@ fn filter_pm_based_on_config<'a>(
.or_else(|| config.0.get("default"))
.and_then(|inner| match payment_method_type {
api_enums::PaymentMethodType::Credit | api_enums::PaymentMethodType::Debit => {
+ let country_currency_filter = inner
+ .0
+ .get(&settings::PaymentMethodFilterKey::PaymentMethodType(
+ *payment_method_type,
+ ))
+ .map(|value| global_country_currency_filter(value, country, currency));
+
card_network_filter(country, currency, card_network, inner);
- payment_attempt
+ let capture_method_filter = payment_attempt
.and_then(|inner| inner.capture_method)
.and_then(|capture_method| {
(capture_method == storage_enums::CaptureMethod::Manual).then(|| {
filter_pm_based_on_capture_method_used(inner, payment_method_type)
})
- })
+ });
+
+ Some(
+ country_currency_filter.unwrap_or(true)
+ && capture_method_filter.unwrap_or(true),
+ )
}
payment_method_type => inner
.0
|
2024-03-13T07:23: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 -->
This PR enables country, currency filter for cards in list payment methods for merchants
### 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)?
-->
Payment Method List needs to be verified for USD and Non-USD payments via BOA:
1. Payments Request(with confirm false):
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: API_KEY_HERE' \
--data-raw '{
"amount": 1404,
"currency": "INR",
"confirm": false,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"customer_id": "CustomerX",
"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": "eqnkl",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "תל אביב",
"state": "California",
"zip": "46282",
"country": "US",
"first_name": "joseph",
"last_name": "ewcjwd"
},
"phone": {
"number": "8056594427",
"country_code": "+97"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"business_label": "food",
"business_country": "US"
}'
```
Payments Response:
```
{
"payment_id": "pay_3ftTdmvei4RVQamsfyfJ",
"merchant_id": "merchant_1706697715",
"status": "requires_payment_method",
"amount": 1404,
"net_amount": 1404,
"amount_capturable": 0,
"amount_received": null,
"connector": null,
"client_secret": "pay_3ftTdmvei4RVQamsfyfJ_secret_SM3IbzER2kXk3jmHe1s2",
"created": "2024-03-13T07:26:39.814Z",
"currency": "INR",
"customer_id": "CustomerX",
"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": null,
"billing": {
"address": {
"city": "תל אביב",
"country": "US",
"line1": "eqnkl",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "46282",
"state": "California",
"first_name": "joseph",
"last_name": "ewcjwd"
},
"phone": {
"number": "8056594427",
"country_code": "+97"
},
"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": "US",
"business_label": "food",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "CustomerX",
"created_at": 1710314799,
"expires": 1710318399,
"secret": "epk_35a516b093434ef6a7bff36ae0efd437"
},
"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_j9PVFpZYzQU1j7yyjkJJ",
"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-03-13T07:41:39.813Z",
"fingerprint": null,
"payment_method_id": null,
"payment_method_status": null
}
```
2. Payment Methods List Request:
```
`curl --location 'http://localhost:8080/account/payment_methods?client_secret=CLIENT_SECRET_HERE' \
--header 'Accept: application/json' \
--header 'api-key: API_KEY_HERE'`
```
Payment Methods List Response:
- For Non-USD Currencies:
```
{
"redirect_url": "https://google.com/success",
"currency": "INR",
"payment_methods": [],
"mandate_payment": null,
"merchant_name": "NewAge Retailer",
"show_surcharge_breakup_screen": false,
"payment_type": "normal"
}
```
- For USD:
```
{
"redirect_url": "https://google.com/success",
"currency": "USD",
"payment_methods": [
{
"payment_method": "wallet",
"payment_method_types": [
{
"payment_method_type": "google_pay",
"payment_experience": [
{
"payment_experience_type": "redirect_to_url",
"eligible_connectors": [
"bankofamerica"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"billing.address.last_name": {
"required_field": "billing.address.last_name",
"display_name": "billing_last_name",
"field_type": "user_billing_name",
"value": "ewcjwd"
},
"billing.address.country": {
"required_field": "billing.address.country",
"display_name": "country",
"field_type": {
"user_address_country": {
"options": [
"ALL"
]
}
},
"value": "US"
},
"billing.address.city": {
"required_field": "billing.address.city",
"display_name": "city",
"field_type": "user_address_city",
"value": "תל אביב"
},
"email": {
"required_field": "email",
"display_name": "email",
"field_type": "user_email_address",
"value": "guest@example.com"
},
"billing.address.line1": {
"required_field": "billing.address.line1",
"display_name": "line1",
"field_type": "user_address_line1",
"value": "eqnkl"
},
"billing.address.first_name": {
"required_field": "billing.address.first_name",
"display_name": "billing_first_name",
"field_type": "user_billing_name",
"value": "joseph"
},
"billing.address.zip": {
"required_field": "billing.address.zip",
"display_name": "zip",
"field_type": "user_address_pincode",
"value": "46282"
},
"billing.address.state": {
"required_field": "billing.address.state",
"display_name": "state",
"field_type": "user_address_state",
"value": "California"
}
},
"surcharge_details": null,
"pm_auth_connector": null
},
{
"payment_method_type": "apple_pay",
"payment_experience": [
{
"payment_experience_type": "invoke_sdk_client",
"eligible_connectors": [
"bankofamerica"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"billing.address.country": {
"required_field": "billing.address.country",
"display_name": "country",
"field_type": {
"user_address_country": {
"options": [
"ALL"
]
}
},
"value": "US"
},
"billing.address.first_name": {
"required_field": "billing.address.first_name",
"display_name": "billing_first_name",
"field_type": "user_billing_name",
"value": "joseph"
},
"billing.address.state": {
"required_field": "billing.address.state",
"display_name": "state",
"field_type": "user_address_state",
"value": "California"
},
"billing.address.last_name": {
"required_field": "billing.address.last_name",
"display_name": "billing_last_name",
"field_type": "user_billing_name",
"value": "ewcjwd"
},
"email": {
"required_field": "email",
"display_name": "email",
"field_type": "user_email_address",
"value": "guest@example.com"
},
"billing.address.city": {
"required_field": "billing.address.city",
"display_name": "city",
"field_type": "user_address_city",
"value": "תל אביב"
},
"billing.address.line1": {
"required_field": "billing.address.line1",
"display_name": "line1",
"field_type": "user_address_line1",
"value": "eqnkl"
},
"billing.address.zip": {
"required_field": "billing.address.zip",
"display_name": "zip",
"field_type": "user_address_pincode",
"value": "46282"
}
},
"surcharge_details": null,
"pm_auth_connector": null
}
]
},
{
"payment_method": "card",
"payment_method_types": [
{
"payment_method_type": "debit",
"payment_experience": null,
"card_networks": [
{
"card_network": "Discover",
"surcharge_details": null,
"eligible_connectors": [
"bankofamerica"
]
},
{
"card_network": "Mastercard",
"surcharge_details": null,
"eligible_connectors": [
"bankofamerica"
]
},
{
"card_network": "Visa",
"surcharge_details": null,
"eligible_connectors": [
"bankofamerica"
]
},
{
"card_network": "JCB",
"surcharge_details": null,
"eligible_connectors": [
"bankofamerica"
]
}
],
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"billing.address.line1": {
"required_field": "billing.address.line1",
"display_name": "line1",
"field_type": "user_address_line1",
"value": "eqnkl"
},
"billing.address.country": {
"required_field": "billing.address.country",
"display_name": "country",
"field_type": {
"user_address_country": {
"options": [
"ALL"
]
}
},
"value": "US"
},
"payment_method_data.card.card_exp_month": {
"required_field": "payment_method_data.card.card_exp_month",
"display_name": "card_exp_month",
"field_type": "user_card_expiry_month",
"value": null
},
"billing.address.state": {
"required_field": "billing.address.state",
"display_name": "state",
"field_type": "user_address_state",
"value": "California"
},
"billing.address.zip": {
"required_field": "billing.address.zip",
"display_name": "zip",
"field_type": "user_address_pincode",
"value": "46282"
},
"payment_method_data.card.card_cvc": {
"required_field": "payment_method_data.card.card_cvc",
"display_name": "card_cvc",
"field_type": "user_card_cvc",
"value": null
},
"billing.address.first_name": {
"required_field": "billing.address.first_name",
"display_name": "billing_first_name",
"field_type": "user_billing_name",
"value": "joseph"
},
"payment_method_data.card.card_exp_year": {
"required_field": "payment_method_data.card.card_exp_year",
"display_name": "card_exp_year",
"field_type": "user_card_expiry_year",
"value": null
},
"email": {
"required_field": "email",
"display_name": "email",
"field_type": "user_email_address",
"value": "guest@example.com"
},
"billing.address.city": {
"required_field": "billing.address.city",
"display_name": "city",
"field_type": "user_address_city",
"value": "תל אביב"
},
"payment_method_data.card.card_number": {
"required_field": "payment_method_data.card.card_number",
"display_name": "card_number",
"field_type": "user_card_number",
"value": null
},
"billing.address.last_name": {
"required_field": "billing.address.last_name",
"display_name": "billing_last_name",
"field_type": "user_billing_name",
"value": "ewcjwd"
}
},
"surcharge_details": null,
"pm_auth_connector": null
},
{
"payment_method_type": "credit",
"payment_experience": null,
"card_networks": [
{
"card_network": "Visa",
"surcharge_details": null,
"eligible_connectors": [
"bankofamerica"
]
},
{
"card_network": "Mastercard",
"surcharge_details": null,
"eligible_connectors": [
"bankofamerica"
]
},
{
"card_network": "JCB",
"surcharge_details": null,
"eligible_connectors": [
"bankofamerica"
]
},
{
"card_network": "Discover",
"surcharge_details": null,
"eligible_connectors": [
"bankofamerica"
]
}
],
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"payment_method_data.card.card_cvc": {
"required_field": "payment_method_data.card.card_cvc",
"display_name": "card_cvc",
"field_type": "user_card_cvc",
"value": null
},
"billing.address.state": {
"required_field": "billing.address.state",
"display_name": "state",
"field_type": "user_address_state",
"value": "California"
},
"billing.address.country": {
"required_field": "billing.address.country",
"display_name": "country",
"field_type": {
"user_address_country": {
"options": [
"ALL"
]
}
},
"value": "US"
},
"payment_method_data.card.card_number": {
"required_field": "payment_method_data.card.card_number",
"display_name": "card_number",
"field_type": "user_card_number",
"value": null
},
"billing.address.city": {
"required_field": "billing.address.city",
"display_name": "city",
"field_type": "user_address_city",
"value": "תל אביב"
},
"payment_method_data.card.card_exp_month": {
"required_field": "payment_method_data.card.card_exp_month",
"display_name": "card_exp_month",
"field_type": "user_card_expiry_month",
"value": null
},
"billing.address.last_name": {
"required_field": "billing.address.last_name",
"display_name": "billing_last_name",
"field_type": "user_billing_name",
"value": "ewcjwd"
},
"payment_method_data.card.card_exp_year": {
"required_field": "payment_method_data.card.card_exp_year",
"display_name": "card_exp_year",
"field_type": "user_card_expiry_year",
"value": null
},
"billing.address.zip": {
"required_field": "billing.address.zip",
"display_name": "zip",
"field_type": "user_address_pincode",
"value": "46282"
},
"billing.address.line1": {
"required_field": "billing.address.line1",
"display_name": "line1",
"field_type": "user_address_line1",
"value": "eqnkl"
},
"billing.address.first_name": {
"required_field": "billing.address.first_name",
"display_name": "billing_first_name",
"field_type": "user_billing_name",
"value": "joseph"
},
"email": {
"required_field": "email",
"display_name": "email",
"field_type": "user_email_address",
"value": "guest@example.com"
}
},
"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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
5c380def254ddc25aa296fa907734f14cf08694b
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4051
|
Bug: [BUG] 3DS Payments through Complete Authorize flow failing
### Bug Description
When doing a 3DS payment that proceeds through the Complete Authorize flow, the token data fetch from Redis fails due to a missing `payment_method` parameter.
### Expected Behavior
The token data fetch from Redis should succeed with the correct token and payment method.
### Actual Behavior
Currently, the token data fetch fails, because it doesn't receive the payment method in the request, but instead is expected to pick it up from the payment attempt, which it's currently not doing.
### Steps To Reproduce
1. Create a Merchant Account, and a Connector account for any connector that uses Complete Authorize flow for 3DS (like Cybersource)
2. Try to make a 3DS payment.
### Context For The Bug
_No response_
### Environment
Are you using hyperswitch hosted version? No
If not (or if building/running locally), please provide the following details:
1. Operating System or Linux distribution: MacOS
2. Rust version (output of `rustc --version`): `1.71.0`
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/payments/operations/payment_complete_authorize.rs b/crates/router/src/core/payments/operations/payment_complete_authorize.rs
index 4e38294d4dd..0f08d14e439 100644
--- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs
+++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs
@@ -131,8 +131,14 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
}
}
- let token_data = if let Some(token) = token.clone() {
- Some(helpers::retrieve_payment_token_data(state, token, payment_method).await?)
+ let token_data = if let Some((token, payment_method)) = token
+ .as_ref()
+ .zip(payment_method.or(payment_attempt.payment_method))
+ {
+ Some(
+ helpers::retrieve_payment_token_data(state, token.clone(), Some(payment_method))
+ .await?,
+ )
} else {
None
};
|
2024-03-13T07:12: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 fixes the issue where token data fetch from Redis was failing for 3DS payments going through the complete authorize flow. The issue being that the payment method was being taken from the request, where it may not be present. The solution was to add the payment method stored in the payment attempt as a fallback.
### 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).
-->
Certain connectors confirm their payments through the Complete Authorize flow when it comes to 3DS. To ensure that the token data fetch for this flow doesn't fail, we should be using the payment attempt as the fallback ground of truth for any missing data. This PR adds this fallback.
## 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)?
-->
3DS Payments with Cybersource (failing before, passing now)
Payment Confirmation:
<img width="962" alt="image" src="https://github.com/juspay/hyperswitch/assets/47862918/95baacc2-a53b-4181-9c02-c75d6d404f96">
Payment Redirection (Succeeding):
<img width="1128" alt="image" src="https://github.com/juspay/hyperswitch/assets/47862918/429fe3a1-c40d-47f2-abe3-ab8f45f90396">
## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
5c380def254ddc25aa296fa907734f14cf08694b
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4049
|
Bug: [BUG] : [Cybersource] Mandate creation condition
### Bug Description
Currently mandate gets created if `mandate_data` is passed in the request which is deprecated
### Expected Behavior
Create mandate with connector if setup_future_usgae: off_session and customer_acceptance is present
### Actual Behavior
Currently mandate gets created if `mandate_data` is passed in the request which is deprecated
### 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/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs
index 60ff508d39c..2fd559680ea 100644
--- a/crates/router/src/connector/cybersource/transformers.rs
+++ b/crates/router/src/connector/cybersource/transformers.rs
@@ -1,5 +1,6 @@
use api_models::payments;
use base64::Engine;
+use common_enums::FutureUsage;
use common_utils::{ext_traits::ValueExt, pii};
use error_stack::{IntoReport, ResultExt};
use masking::{ExposeInterface, PeekInterface, Secret};
@@ -500,47 +501,54 @@ impl
Option<String>,
),
) -> Result<Self, Self::Error> {
- let (action_list, action_token_types, authorization_options) =
- if item.router_data.request.setup_mandate_details.is_some() {
- (
- Some(vec![CybersourceActionsList::TokenCreate]),
- Some(vec![CybersourceActionsTokenType::PaymentInstrument]),
- Some(CybersourceAuthorizationOptions {
- initiator: Some(CybersourcePaymentInitiator {
- initiator_type: Some(CybersourcePaymentInitiatorTypes::Customer),
- credential_stored_on_file: Some(true),
- stored_credential_used: None,
- }),
- merchant_intitiated_transaction: None,
+ let (action_list, action_token_types, authorization_options) = if item
+ .router_data
+ .request
+ .setup_future_usage
+ .map_or(false, |future_usage| {
+ matches!(future_usage, FutureUsage::OffSession)
+ })
+ && item.router_data.request.customer_acceptance.is_some()
+ {
+ (
+ Some(vec![CybersourceActionsList::TokenCreate]),
+ Some(vec![CybersourceActionsTokenType::PaymentInstrument]),
+ Some(CybersourceAuthorizationOptions {
+ initiator: Some(CybersourcePaymentInitiator {
+ initiator_type: Some(CybersourcePaymentInitiatorTypes::Customer),
+ credential_stored_on_file: Some(true),
+ stored_credential_used: None,
}),
- )
- } else if item.router_data.request.connector_mandate_id().is_some() {
- let original_amount = item
- .router_data
- .get_recurring_mandate_payment_data()?
- .get_original_payment_amount()?;
- let original_currency = item
- .router_data
- .get_recurring_mandate_payment_data()?
- .get_original_payment_currency()?;
- (
- None,
- None,
- Some(CybersourceAuthorizationOptions {
- initiator: None,
- merchant_intitiated_transaction: Some(MerchantInitiatedTransaction {
- reason: None,
- original_authorized_amount: Some(utils::get_amount_as_string(
- &types::api::CurrencyUnit::Base,
- original_amount,
- original_currency,
- )?),
- }),
+ merchant_intitiated_transaction: None,
+ }),
+ )
+ } else if item.router_data.request.connector_mandate_id().is_some() {
+ let original_amount = item
+ .router_data
+ .get_recurring_mandate_payment_data()?
+ .get_original_payment_amount()?;
+ let original_currency = item
+ .router_data
+ .get_recurring_mandate_payment_data()?
+ .get_original_payment_currency()?;
+ (
+ None,
+ None,
+ Some(CybersourceAuthorizationOptions {
+ initiator: None,
+ merchant_intitiated_transaction: Some(MerchantInitiatedTransaction {
+ reason: None,
+ original_authorized_amount: Some(utils::get_amount_as_string(
+ &types::api::CurrencyUnit::Base,
+ original_amount,
+ original_currency,
+ )?),
}),
- )
- } else {
- (None, None, None)
- };
+ }),
+ )
+ } else {
+ (None, None, None)
+ };
let commerce_indicator = match network {
Some(card_network) => match card_network.to_lowercase().as_str() {
"amex" => "aesk",
@@ -581,23 +589,30 @@ impl
&CybersourceConsumerAuthValidateResponse,
),
) -> Self {
- let (action_list, action_token_types, authorization_options) =
- if item.router_data.request.setup_future_usage.is_some() {
- (
- Some(vec![CybersourceActionsList::TokenCreate]),
- Some(vec![CybersourceActionsTokenType::PaymentInstrument]),
- Some(CybersourceAuthorizationOptions {
- initiator: Some(CybersourcePaymentInitiator {
- initiator_type: Some(CybersourcePaymentInitiatorTypes::Customer),
- credential_stored_on_file: Some(true),
- stored_credential_used: None,
- }),
- merchant_intitiated_transaction: None,
+ let (action_list, action_token_types, authorization_options) = if item
+ .router_data
+ .request
+ .setup_future_usage
+ .map_or(false, |future_usage| {
+ matches!(future_usage, FutureUsage::OffSession)
+ })
+ //TODO check for customer acceptance also
+ {
+ (
+ Some(vec![CybersourceActionsList::TokenCreate]),
+ Some(vec![CybersourceActionsTokenType::PaymentInstrument]),
+ Some(CybersourceAuthorizationOptions {
+ initiator: Some(CybersourcePaymentInitiator {
+ initiator_type: Some(CybersourcePaymentInitiatorTypes::Customer),
+ credential_stored_on_file: Some(true),
+ stored_credential_used: None,
}),
- )
- } else {
- (None, None, None)
- };
+ merchant_intitiated_transaction: None,
+ }),
+ )
+ } else {
+ (None, None, None)
+ };
Self {
capture: Some(matches!(
item.router_data.request.capture_method,
|
2024-03-12T17:00:50Z
|
## 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 -->
Create mandate with connector if `setup_future_usgae: off_session` and `customer_acceptance` is present.
### 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).
-->
#4049
## 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 Mandate Payment
```
curl --location 'http://localhost:8080/payments' \
--header 'Accept: application/json' \
--header 'Content-Type: application/json' \
--header 'api-key: dev_j23UDZ4X6JcYN6Jz3esn78yIMGYYCEjA3oCBvwogG8vqb8AjGnFGRMezdSkxlJDX' \
--data-raw '{
"amount": 2810,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"customer_id": "shanks5",
"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",
"statement_descriptor_name": "Juspay",
"statement_descriptor_suffix": "Router",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4456530000001096",
"card_exp_month": "01",
"card_exp_year": "2027",
"card_holder_name": "joseph Doe",
"card_cvc": "100"
}
},
"billing": {
"address": {
"city": "SanFransico",
"country": "AE",
"line1": "hdh",
"line2": "HarrisonStreet",
"line3": "HarrisonStreet",
"zip": "94122",
"state": "California",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"setup_future_usage": "off_session",
"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 recurring Payment
```
curl --location 'http://localhost:8080/payments/pay_7AdU4tNk55yv7dLMEvT7/confirm' \
--header 'Accept: application/json' \
--header 'Content-Type: application/json' \
--header 'api-key: dev_xsGUpiN8xzYbVBQBfbjRWhFi9JfoppTJZtV6mgwp6w5oG87TD0BLRztSyDlo9pBu' \
--data '{
"payment_token": "token_JZSFn3jCe8usurf8ofcF",
"payment_method": "card"
}'
```
## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
3eff4ebd3a60b5831cbec0158527475c8f7d7eb4
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4037
|
Bug: Filter wallet payment method from mca based on customer pm
https://github.com/juspay/hyperswitch/issues/3741
Apple pay wallet is getting filtered out from list merchant payment method if the customer has saved it already. This has to be done for all wallets
|
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index fccacfef45d..985ddcfe849 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -1344,42 +1344,50 @@ pub async fn list_payment_methods(
.await?;
}
- // Filter out applepay payment method from mca if customer has already saved it
- response
- .iter()
- .position(|pm| {
- pm.payment_method == enums::PaymentMethod::Wallet
- && pm.payment_method_type == enums::PaymentMethodType::ApplePay
- })
+ // Filter out wallet payment method from mca if customer has already saved it
+ customer
.as_ref()
- .zip(customer.as_ref())
- .async_map(|(index, customer)| async {
- match db
- .find_payment_method_by_customer_id_merchant_id_list(
- &customer.customer_id,
- &merchant_account.merchant_id,
- None,
- )
- .await
- {
- Ok(customer_payment_methods) => {
- if customer_payment_methods.iter().any(|pm| {
- pm.payment_method == enums::PaymentMethod::Wallet
- && pm.payment_method_type == Some(enums::PaymentMethodType::ApplePay)
- }) {
- response.remove(*index);
- }
- Ok(())
- }
- Err(error) => {
- if error.current_context().is_db_not_found() {
+ .async_map(|customer| async {
+ let wallet_pm_exists = response
+ .iter()
+ .any(|mca| mca.payment_method == enums::PaymentMethod::Wallet);
+ if wallet_pm_exists {
+ match db
+ .find_payment_method_by_customer_id_merchant_id_list(
+ &customer.customer_id,
+ &merchant_account.merchant_id,
+ None,
+ )
+ .await
+ {
+ Ok(customer_payment_methods) => {
+ let customer_wallet_pm = customer_payment_methods
+ .iter()
+ .filter(|cust_pm| {
+ cust_pm.payment_method == enums::PaymentMethod::Wallet
+ })
+ .collect::<Vec<_>>();
+
+ response.retain(|mca| {
+ !(mca.payment_method == enums::PaymentMethod::Wallet
+ && customer_wallet_pm.iter().any(|cust_pm| {
+ cust_pm.payment_method_type == Some(mca.payment_method_type)
+ }))
+ });
Ok(())
- } else {
- Err(error)
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("failed to find payment methods for a customer")
+ }
+ Err(error) => {
+ if error.current_context().is_db_not_found() {
+ Ok(())
+ } else {
+ Err(error)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("failed to find payment methods for a customer")
+ }
}
}
+ } else {
+ Ok(())
}
})
.await
|
2024-03-11T16:56:04Z
|
## 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 -->
https://github.com/juspay/hyperswitch/pull/3953
Similar to above issue but now the PR refactors to filter out any wallet payment method from mca if it is saved by a customer
### 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. Create mca
```
curl --location 'http://localhost:8080/account/merchant_1709561576/connectors' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"connector_type": "fiz_operations",
"connector_name": "stripe",
"connector_account_details": {
"auth_type": "HeaderKey",
"api_key": "abc"
},
"test_mode": false,
"disabled": false,
"payment_methods_enabled": [
{
"payment_method": "card",
"payment_method_types": [
{
"payment_method_type": "credit",
"card_networks": [
"Visa",
"Mastercard"
],
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "debit",
"card_networks": [
"Visa",
"Mastercard"
],
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
},
{
"payment_method": "bank_debit",
"payment_method_types": [
{
"payment_method_type": "ach",
"recurring_enabled": true,
"installment_payment_enabled": true,
"minimum_amount": 0,
"maximum_amount": 10000
}
]
},
{
"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_type": "google_pay",
"payment_experience": "invoke_sdk_client",
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
}
],
"metadata": {
"apple_pay_combined": {
"manual": {
"session_token_data": {
"initiative": "web",
"certificate": "certificate",
"display_name": "applepay",
"certificate_keys": "keys",
"initiative_context": "sdk-test-app.netlify.app",
"merchant_identifier": "xyz"
},
"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": "abc"
}
}
}
]
}
},
"connector_webhook_details": {
"merchant_secret": "MyWebhookSecret"
},
"business_country": "US",
"business_label": "default"
}'
```
2. Create a applepay or googlepay wallet payment so that wallet entry gets saved in `payment_methods` table
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_UyebBGu4SpiswmyxyM5ISeJO5BoAVQO8yWX20QFoKFBwB7q50t23zvH3xRqQ6auv' \
--data-raw '{
"amount": 650,
"currency": "USD",
"confirm": true,
"business_country": "US",
"business_label": "default",
"amount_to_capture": 650,
"customer_id": "{{customer_id}}",
"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",
"setup_future_usage": "on_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"
}
},
"payment_method_data": {
"wallet": {
"apple_pay": {
"payment_data": "xyz",
"payment_method": {
"display_name": "Visa 0326",
"network": "Mastercard",
"type": "debit"
},
"transaction_identifier": "abc"
}
}
},
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "in sit",
"user_agent": "amet irure esse"
}
}
}'
```
3. Do `list_customer_payment_method`. Find the wallet entry and get the `payment_method_id` from response
4. Now do a payment with any payment method with `confirm = false`
5. Do list MCA with `client_secret`
```
curl --location 'http://localhost:8080/account/payment_methods?client_secret=abc' \
--header 'Accept: application/json' \
--header 'api-key: abc' \
--data ''
```
6. The payment method which u saved earlier shoudn't be listed in the result
7. Check with saving both google_pay and apple_pay to customer (In this case both has to be filtered when done list mca)
## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
e87f2ea8c5669473940df8bc2f5c61fdf3f218ff
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4047
|
Bug: [BUG] : [Adyen] Production URL endpoint
### Bug Description
For Adyen production URL endpoint is not correctly configured as compared to how it is used
### Expected Behavior
`/` is missing in the end for production endpoint
### Actual Behavior
For Adyen production URL endpoint is not correctly configured as compared to how it is used
### 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/config/deployments/production.toml b/config/deployments/production.toml
index 892f11e9415..a6a37858308 100644
--- a/config/deployments/production.toml
+++ b/config/deployments/production.toml
@@ -17,7 +17,7 @@ payout_connector_list = "wise"
[connectors]
aci.base_url = "https://eu-test.oppwa.com/"
-adyen.base_url = "https://{{merchant_endpoint_prefix}}-checkout-live.adyenpayments.com/checkout"
+adyen.base_url = "https://{{merchant_endpoint_prefix}}-checkout-live.adyenpayments.com/checkout/"
adyen.secondary_base_url = "https://{{merchant_endpoint_prefix}}-pal-live.adyenpayments.com/"
airwallex.base_url = "https://api-demo.airwallex.com/"
applepay.base_url = "https://apple-pay-gateway.apple.com/"
diff --git a/crates/router/src/connector/adyen.rs b/crates/router/src/connector/adyen.rs
index 67e319ddc22..d79761da472 100644
--- a/crates/router/src/connector/adyen.rs
+++ b/crates/router/src/connector/adyen.rs
@@ -1761,7 +1761,7 @@ impl api::IncomingWebhook for Adyen {
}
if adyen::is_refund_event(¬if.event_code) {
return Ok(api_models::webhooks::ObjectReferenceId::RefundId(
- api_models::webhooks::RefundIdType::ConnectorRefundId(notif.psp_reference),
+ api_models::webhooks::RefundIdType::RefundId(notif.merchant_reference),
));
}
if adyen::is_chargeback_event(¬if.event_code) {
diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs
index 1eede78503b..cff6c7a8d99 100644
--- a/crates/router/src/connector/adyen/transformers.rs
+++ b/crates/router/src/connector/adyen/transformers.rs
@@ -1128,6 +1128,7 @@ pub struct AdyenCard {
expiry_month: Secret<String>,
expiry_year: Secret<String>,
cvc: Option<Secret<String>>,
+ holder_name: Option<Secret<String>>,
brand: Option<CardBrand>, //Mandatory for mandate using network_txns_id
network_payment_reference: Option<Secret<String>>,
}
@@ -1980,6 +1981,7 @@ impl<'a> TryFrom<&api::Card> for AdyenPaymentMethod<'a> {
expiry_month: card.card_exp_month.clone(),
expiry_year: card.get_expiry_year_4_digit(),
cvc: Some(card.card_cvc.clone()),
+ holder_name: card.card_holder_name.clone(),
brand: None,
network_payment_reference: None,
};
@@ -2584,6 +2586,7 @@ impl<'a>
expiry_month: card.card_exp_month.clone(),
expiry_year: card.card_exp_year.clone(),
cvc: None,
+ holder_name: card.card_holder_name.clone(),
brand: Some(brand),
network_payment_reference: Some(Secret::new(network_mandate_id)),
};
|
2024-03-12T12:58:21Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [X] Bugfix
- [ ] New feature
- [X] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
- Update Prod URL endpoint
- Handle refunds webhooks using hyperswitch internal refund id
- Add card holder name
### 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`
-->
Updated Prod URL endpoint
## 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).
-->
#4047
## 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)?
-->
- Trigger a refunds transaction
```
curl --location 'http://localhost:8080/refunds' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_gwfA0IT4jpKdcUSmJlWMJ0jawjc5ziP6lA91du0gpc9ydEzI5HajDN18Wr72NkS7' \
--data '{
"payment_id": "pay_ow2YSNvgVDZlGTv3o8wc",
"reason": "RETURN",
"refund_type": "instant",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}'
```
- Check for outgoing webhook and also retrieve the refund to confirm the Status change

- Send card holder name in the cards request it should be visible in Adyen Dashboard for the payment
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_gwfA0IT4jpKdcUSmJlWMJ0jawjc5ziP6lA91du0gpc9ydEzI5HajDN18Wr72NkS7' \
--data-raw '{
"amount": 6540,
"currency": "EUR",
"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",
"profile_id": "pro_8Ix85cVgHD3x4DQIFZTV",
"business_country": "US",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "371449635398431",
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": "joseph Doe",
"card_cvc": "7373"
}
},
"routing": {
"type": "single",
"data": "adyen"
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "DE",
"first_name": "PiX"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "PiX"
}
},
"statement_descriptor_name": "This is me making a statement",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}'
```
## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
708cce926125a29b406db48cf0ebd35b217927d4
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4036
|
Bug: [BUG] [AUTHORIZEDOTNET] Connector Audit
### Bug Description
Authorizedotnet Connector Audit fixes.
1. Production endpoint is wrong
2. Connector Transaction ID is not passed in 2XX Error Response
3. Default case handling in code
### Expected Behavior
Authorizedotnet Connector Audit fixes.
1. Production endpoint should be https://api.authorize.net/xml/v1/request.api.
2. Connector Transaction ID should be passed to 2XX Error Response.
3. Default case handling should not be present in code.
### Actual Behavior
Authorizedotnet Connector Audit fixes.
1. Production endpoint is wrong
2. Connector Transaction ID is not passed in 2XX Error Response
3. Default case handling in code
### 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/config/deployments/production.toml b/config/deployments/production.toml
index 892f11e9415..6bfcad3ad50 100644
--- a/config/deployments/production.toml
+++ b/config/deployments/production.toml
@@ -21,7 +21,7 @@ adyen.base_url = "https://{{merchant_endpoint_prefix}}-checkout-live.adyenpaymen
adyen.secondary_base_url = "https://{{merchant_endpoint_prefix}}-pal-live.adyenpayments.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"
+authorizedotnet.base_url = "https://api.authorize.net/xml/v1/request.api"
bambora.base_url = "https://api.na.bambora.com"
bankofamerica.base_url = "https://api.merchant-services.bankofamerica.com/"
bitpay.base_url = "https://bitpay.com"
diff --git a/crates/router/src/connector/authorizedotnet.rs b/crates/router/src/connector/authorizedotnet.rs
index 0aba48fa5e5..be02b4524f8 100644
--- a/crates/router/src/connector/authorizedotnet.rs
+++ b/crates/router/src/connector/authorizedotnet.rs
@@ -685,8 +685,8 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
let intermediate_response =
bytes::Bytes::copy_from_slice(intermediate_response.0.as_bytes());
- let response: authorizedotnet::AuthorizedotnetSyncResponse = intermediate_response
- .parse_struct("AuthorizedotnetSyncResponse")
+ let response: authorizedotnet::AuthorizedotnetRSyncResponse = intermediate_response
+ .parse_struct("AuthorizedotnetRSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
@@ -872,11 +872,17 @@ impl api::IncomingWebhook for Authorizedotnet {
),
))
}
- _ => Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
- api_models::payments::PaymentIdType::ConnectorTransactionId(
- authorizedotnet::get_trans_id(&details)?,
- ),
- )),
+ authorizedotnet::AuthorizedotnetWebhookEvent::AuthorizationCreated
+ | authorizedotnet::AuthorizedotnetWebhookEvent::PriorAuthCapture
+ | authorizedotnet::AuthorizedotnetWebhookEvent::AuthCapCreated
+ | authorizedotnet::AuthorizedotnetWebhookEvent::CaptureCreated
+ | authorizedotnet::AuthorizedotnetWebhookEvent::VoidCreated => {
+ Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
+ api_models::payments::PaymentIdType::ConnectorTransactionId(
+ authorizedotnet::get_trans_id(&details)?,
+ ),
+ ))
+ }
}
}
diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs
index 5d3a7d0054f..4a79b179b84 100644
--- a/crates/router/src/connector/authorizedotnet/transformers.rs
+++ b/crates/router/src/connector/authorizedotnet/transformers.rs
@@ -190,44 +190,48 @@ fn get_pm_and_subsequent_auth_detail(
}
}
}
- _ => match item.router_data.request.payment_method_data {
- api::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,
- }),
+ Some(api_models::payments::MandateReferenceId::ConnectorMandateId(_)) | None => {
+ match item.router_data.request.payment_method_data {
+ api::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,
+ ))
+ }
+ api::PaymentMethodData::Wallet(ref wallet_data) => Ok((
+ get_wallet_data(
+ wallet_data,
+ &item.router_data.request.complete_authorize_url,
+ )?,
+ None,
None,
- ))
+ )),
+ api::PaymentMethodData::CardRedirect(_)
+ | api::PaymentMethodData::PayLater(_)
+ | api::PaymentMethodData::BankRedirect(_)
+ | api::PaymentMethodData::BankDebit(_)
+ | api::PaymentMethodData::BankTransfer(_)
+ | api::PaymentMethodData::Crypto(_)
+ | api::PaymentMethodData::MandatePayment
+ | api::PaymentMethodData::Reward
+ | api::PaymentMethodData::Upi(_)
+ | api::PaymentMethodData::Voucher(_)
+ | api::PaymentMethodData::GiftCard(_)
+ | api::PaymentMethodData::CardToken(_) => {
+ Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("authorizedotnet"),
+ ))?
+ }
}
- api::PaymentMethodData::Wallet(ref wallet_data) => Ok((
- get_wallet_data(
- wallet_data,
- &item.router_data.request.complete_authorize_url,
- )?,
- None,
- None,
- )),
- api::PaymentMethodData::CardRedirect(_)
- | api::PaymentMethodData::PayLater(_)
- | api::PaymentMethodData::BankRedirect(_)
- | api::PaymentMethodData::BankDebit(_)
- | api::PaymentMethodData::BankTransfer(_)
- | api::PaymentMethodData::Crypto(_)
- | api::PaymentMethodData::MandatePayment
- | api::PaymentMethodData::Reward
- | api::PaymentMethodData::Upi(_)
- | api::PaymentMethodData::Voucher(_)
- | api::PaymentMethodData::GiftCard(_)
- | api::PaymentMethodData::CardToken(_) => Err(errors::ConnectorError::NotImplemented(
- utils::get_unimplemented_payment_method_error_message("authorizedotnet"),
- ))?,
- },
+ }
}
}
@@ -382,7 +386,7 @@ impl TryFrom<&AuthorizedotnetRouterData<&types::PaymentsAuthorizeRouterData>>
country: address.country,
});
let transaction_request = TransactionRequest {
- transaction_type: TransactionType::from(item.router_data.request.capture_method),
+ transaction_type: TransactionType::try_from(item.router_data.request.capture_method)?,
amount: item.amount,
currency_code: item.router_data.request.currency.to_string(),
payment: payment_details,
@@ -662,7 +666,7 @@ impl<F, T>
reason: None,
status_code: item.http_code,
attempt_status: None,
- connector_transaction_id: None,
+ connector_transaction_id: Some(transaction_response.transaction_id.clone()),
})
});
let metadata = transaction_response
@@ -740,7 +744,7 @@ impl<F, T>
reason: None,
status_code: item.http_code,
attempt_status: None,
- connector_transaction_id: None,
+ connector_transaction_id: Some(transaction_response.transaction_id.clone()),
})
});
let metadata = transaction_response
@@ -886,7 +890,7 @@ impl<F> TryFrom<types::RefundsResponseRouterData<F, AuthorizedotnetRefundRespons
reason: None,
status_code: item.http_code,
attempt_status: None,
- connector_transaction_id: None,
+ connector_transaction_id: Some(transaction_response.transaction_id.clone()),
})
});
@@ -976,6 +980,15 @@ pub enum SyncStatus {
FDSPendingReview,
}
+#[derive(Debug, Deserialize, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub enum RSyncStatus {
+ RefundSettledSuccessfully,
+ RefundPendingSettlement,
+ Declined,
+ GeneralError,
+}
+
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SyncTransactionResponse {
@@ -990,14 +1003,18 @@ pub struct AuthorizedotnetSyncResponse {
messages: ResponseMessages,
}
-impl From<SyncStatus> for enums::RefundStatus {
- fn from(transaction_status: SyncStatus) -> Self {
- match transaction_status {
- SyncStatus::RefundSettledSuccessfully => Self::Success,
- SyncStatus::RefundPendingSettlement => Self::Pending,
- _ => Self::Failure,
- }
- }
+#[derive(Debug, Deserialize, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct RSyncTransactionResponse {
+ #[serde(rename = "transId")]
+ transaction_id: String,
+ transaction_status: RSyncStatus,
+}
+
+#[derive(Debug, Deserialize, Serialize)]
+pub struct AuthorizedotnetRSyncResponse {
+ transaction: Option<RSyncTransactionResponse>,
+ messages: ResponseMessages,
}
impl From<SyncStatus> for enums::AttemptStatus {
@@ -1017,13 +1034,23 @@ impl From<SyncStatus> for enums::AttemptStatus {
}
}
-impl TryFrom<types::RefundsResponseRouterData<api::RSync, AuthorizedotnetSyncResponse>>
+impl From<RSyncStatus> for enums::RefundStatus {
+ fn from(transaction_status: RSyncStatus) -> Self {
+ match transaction_status {
+ RSyncStatus::RefundSettledSuccessfully => Self::Success,
+ RSyncStatus::RefundPendingSettlement => Self::Pending,
+ RSyncStatus::Declined | RSyncStatus::GeneralError => Self::Failure,
+ }
+ }
+}
+
+impl TryFrom<types::RefundsResponseRouterData<api::RSync, AuthorizedotnetRSyncResponse>>
for types::RefundsRouterData<api::RSync>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::RefundsResponseRouterData<api::RSync, AuthorizedotnetSyncResponse>,
+ item: types::RefundsResponseRouterData<api::RSync, AuthorizedotnetRSyncResponse>,
) -> Result<Self, Self::Error> {
match item.response.transaction {
Some(transaction) => {
@@ -1108,11 +1135,24 @@ fn construct_refund_payment_details(masked_number: String) -> PaymentDetails {
})
}
-impl From<Option<enums::CaptureMethod>> for TransactionType {
- fn from(capture_method: Option<enums::CaptureMethod>) -> Self {
+impl TryFrom<Option<enums::CaptureMethod>> for TransactionType {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(capture_method: Option<enums::CaptureMethod>) -> Result<Self, Self::Error> {
match capture_method {
- Some(enums::CaptureMethod::Manual) => Self::Authorization,
- _ => Self::Payment,
+ Some(enums::CaptureMethod::Manual) => Ok(Self::Authorization),
+ Some(enums::CaptureMethod::Automatic) | None => Ok(Self::Payment),
+ Some(enums::CaptureMethod::ManualMultiple) => {
+ Err(utils::construct_not_supported_error_report(
+ enums::CaptureMethod::ManualMultiple,
+ "authorizedotnet",
+ ))?
+ }
+ Some(enums::CaptureMethod::Scheduled) => {
+ Err(utils::construct_not_supported_error_report(
+ enums::CaptureMethod::Scheduled,
+ "authorizedotnet",
+ ))?
+ }
}
}
}
@@ -1359,9 +1399,19 @@ impl TryFrom<&AuthorizedotnetRouterData<&types::PaymentsCompleteAuthorizeRouterD
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?
.payer_id;
let transaction_type = match item.router_data.request.capture_method {
- Some(enums::CaptureMethod::Manual) => TransactionType::ContinueAuthorization,
- _ => TransactionType::ContinueCapture,
- };
+ Some(enums::CaptureMethod::Manual) => Ok(TransactionType::ContinueAuthorization),
+ Some(enums::CaptureMethod::Automatic) | None => Ok(TransactionType::ContinueCapture),
+ Some(enums::CaptureMethod::ManualMultiple) => {
+ Err(errors::ConnectorError::NotSupported {
+ message: enums::CaptureMethod::ManualMultiple.to_string(),
+ connector: "authorizedotnet",
+ })
+ }
+ Some(enums::CaptureMethod::Scheduled) => Err(errors::ConnectorError::NotSupported {
+ message: enums::CaptureMethod::Scheduled.to_string(),
+ connector: "authorizedotnet",
+ }),
+ }?;
let transaction_request = TransactionConfirmRequest {
transaction_type,
payment: PaypalPaymentConfirm {
|
2024-03-11T13:26: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 -->
Authorizedotnet Connector Audit fixes:
1. Production endpoint fixed.
2. Connector Transaction ID added to 2XX Error Response
3. Default case handling removed
### 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`
4. `crates/router/src/configs`
5. `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/4036
## 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)?
-->
Testing needs to be done by creating a 2XX error for a payment via authorizedotnet.
2XX error can be generated by doing 2 back to back transactions with same request body which will trigger a dupliacte transaction error at connector end.
Request:
```curl
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_5WytrFNU7ci62yt6DYvmVVcyVdMG6s92tlbiS9vWLsWgdud2qIDqvPhvfquNza5X' \
--data '{
"amount": 1234,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"customer_id": "StripeCustomer",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "5424000000000015",
"card_exp_month": "02",
"card_exp_year": "35",
"card_holder_name": "John Doe",
"card_cvc": "123"
}
},
"billing": {
"address": {
"first_name": "John",
"last_name": "Doe",
"line1": "Harrison Street",
"city": "San Francisco",
"state": "California",
"zip": "94016",
"country": "US"
}
},
"setup_future_usage": "on_session"
}'
```
Failure Response:
```json
{
"payment_id": "pay_2LFVZlFX0KHdneXkkZSp",
"merchant_id": "merchant_1709720492",
"status": "failed",
"amount": 1234,
"net_amount": 1234,
"amount_capturable": 0,
"amount_received": null,
"connector": "authorizedotnet",
"client_secret": "pay_2LFVZlFX0KHdneXkkZSp_secret_34pXGRBkphSF4qARev7i",
"created": "2024-03-11T13:54:27.251Z",
"currency": "USD",
"customer_id": "StripeCustomer",
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": "on_session",
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "0015",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "542400",
"card_extended_bin": "54240000",
"card_exp_month": "02",
"card_exp_year": "35",
"card_holder_name": "John Doe"
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": {
"address": {
"city": "San Francisco",
"country": "US",
"line1": "Harrison Street",
"line2": null,
"line3": null,
"zip": "94016",
"state": "California",
"first_name": "John",
"last_name": "Doe"
},
"phone": {
"number": null,
"country_code": null
},
"email": 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": "11",
"error_message": "A duplicate transaction has been submitted.",
"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": 1710165267,
"expires": 1710168867,
"secret": "epk_e39c6817cc0c4abdb7cb8081cf601417"
},
"manual_retry_allowed": true,
"connector_transaction_id": "0",
"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": false,
"authorization_count": null,
"incremental_authorizations": null,
"external_authentication_details": null,
"request_external_3ds_authentication": null,
"expires_on": "2024-03-11T14:09:27.251Z",
"fingerprint": null,
"payment_method_id": null,
"payment_method_status": null
}
```
Now check in DB whether connector_transaction_id is getting populated for the failure scenario:
<img width="435" alt="Screenshot 2024-03-11 at 7 30 05 PM" src="https://github.com/juspay/hyperswitch/assets/41580413/42843ae3-cc0e-4323-81a5-641c4dc38d5b">
## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
ce3625cb0cdccc750a073c012f0e541b014c3190
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4070
|
Bug: [BUG] Fix postman collections
- [x] NMI: Scenarios 10 and 11 are run before 1
- [x] Bluesnap: Inconsistency of payment method being saved in saved card flow
- [x] Checkout: Inconsistency of payment method being saved in saved card flow
- [x]Adyen: Inconsistency of payment method being saved in saved card flow
## Solution
- Remove `Copy` in Scenarios 10 and 11 form `.meta.json` to match with actual folder names
- Set `random_number` in `pre_request.js` for Bluesnap connector to make `customer_id` unique
|
diff --git a/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario10-Save card flow/Payments - Create/event.prerequest.js b/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario10-Save card flow/Payments - Create/event.prerequest.js
new file mode 100644
index 00000000000..27965bb9c01
--- /dev/null
+++ b/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario10-Save card flow/Payments - Create/event.prerequest.js
@@ -0,0 +1 @@
+pm.environment.set("random_number", _.random(1000, 100000));
diff --git a/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario11-Pass Invalid CVV for save card flow and verify failed payment Copy/Payments - Create/event.prerequest.js b/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario11-Pass Invalid CVV for save card flow and verify failed payment Copy/Payments - Create/event.prerequest.js
new file mode 100644
index 00000000000..27965bb9c01
--- /dev/null
+++ b/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario11-Pass Invalid CVV for save card flow and verify failed payment Copy/Payments - Create/event.prerequest.js
@@ -0,0 +1 @@
+pm.environment.set("random_number", _.random(1000, 100000));
diff --git a/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture Copy/Payments - Create/event.prerequest.js b/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture Copy/Payments - Create/event.prerequest.js
new file mode 100644
index 00000000000..27965bb9c01
--- /dev/null
+++ b/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture Copy/Payments - Create/event.prerequest.js
@@ -0,0 +1 @@
+pm.environment.set("random_number", _.random(1000, 100000));
diff --git a/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment Copy/Payments - Create/event.prerequest.js b/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment Copy/Payments - Create/event.prerequest.js
new file mode 100644
index 00000000000..27965bb9c01
--- /dev/null
+++ b/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment Copy/Payments - Create/event.prerequest.js
@@ -0,0 +1 @@
+pm.environment.set("random_number", _.random(1000, 100000));
diff --git a/postman/collection-dir/checkout/Flow Testcases/Happy Cases/Scenario11-Save card flow/Payments - Create/event.prerequest.js b/postman/collection-dir/checkout/Flow Testcases/Happy Cases/Scenario11-Save card flow/Payments - Create/event.prerequest.js
new file mode 100644
index 00000000000..27965bb9c01
--- /dev/null
+++ b/postman/collection-dir/checkout/Flow Testcases/Happy Cases/Scenario11-Save card flow/Payments - Create/event.prerequest.js
@@ -0,0 +1 @@
+pm.environment.set("random_number", _.random(1000, 100000));
diff --git a/postman/collection-dir/checkout/Flow Testcases/Happy Cases/Scenario12-Don't Pass CVV for save card flow and verify success payment/Payments - Create/event.prerequest.js b/postman/collection-dir/checkout/Flow Testcases/Happy Cases/Scenario12-Don't Pass CVV for save card flow and verify success payment/Payments - Create/event.prerequest.js
new file mode 100644
index 00000000000..27965bb9c01
--- /dev/null
+++ b/postman/collection-dir/checkout/Flow Testcases/Happy Cases/Scenario12-Don't Pass CVV for save card flow and verify success payment/Payments - Create/event.prerequest.js
@@ -0,0 +1 @@
+pm.environment.set("random_number", _.random(1000, 100000));
diff --git a/postman/collection-dir/checkout/Flow Testcases/Happy Cases/Scenario13-Pass Invalid CVV for save card flow and verify failed payment/Payments - Create/event.prerequest.js b/postman/collection-dir/checkout/Flow Testcases/Happy Cases/Scenario13-Pass Invalid CVV for save card flow and verify failed payment/Payments - Create/event.prerequest.js
new file mode 100644
index 00000000000..27965bb9c01
--- /dev/null
+++ b/postman/collection-dir/checkout/Flow Testcases/Happy Cases/Scenario13-Pass Invalid CVV for save card flow and verify failed payment/Payments - Create/event.prerequest.js
@@ -0,0 +1 @@
+pm.environment.set("random_number", _.random(1000, 100000));
diff --git a/postman/collection-dir/checkout/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Create/event.prerequest.js b/postman/collection-dir/checkout/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Create/event.prerequest.js
new file mode 100644
index 00000000000..27965bb9c01
--- /dev/null
+++ b/postman/collection-dir/checkout/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Create/event.prerequest.js
@@ -0,0 +1 @@
+pm.environment.set("random_number", _.random(1000, 100000));
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/.meta.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/.meta.json
index 035bfeded8e..ad1de26c594 100644
--- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/.meta.json
+++ b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/.meta.json
@@ -12,8 +12,8 @@
"Scenario8-Create a failure card payment with confirm true",
"Scenario9-Update amount with automatic capture",
"Scenario9a-Update amount with manual capture",
- "Scenario10-Create a mandate and recurring payment Copy",
- "Scenario11-Refund recurring payment Copy",
+ "Scenario10-Create a mandate and recurring payment",
+ "Scenario11-Refund recurring payment",
"Scenario12-Add card flow",
"Scenario13-Don't Pass CVV for save card flow and verify success payment",
"Scenario14-Save card payment with manual capture",
diff --git a/postman/collection-json/bluesnap.postman_collection.json b/postman/collection-json/bluesnap.postman_collection.json
index e8160e482fe..137ccbe1a23 100644
--- a/postman/collection-json/bluesnap.postman_collection.json
+++ b/postman/collection-json/bluesnap.postman_collection.json
@@ -837,6 +837,16 @@
{
"name": "Payments - Create",
"event": [
+ {
+ "listen": "prerequest",
+ "script": {
+ "exec": [
+ "pm.environment.set(\"random_number\", _.random(1000, 100000));",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ },
{
"listen": "test",
"script": {
@@ -1811,6 +1821,16 @@
{
"name": "Payments - Create",
"event": [
+ {
+ "listen": "prerequest",
+ "script": {
+ "exec": [
+ "pm.environment.set(\"random_number\", _.random(1000, 100000));",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ },
{
"listen": "test",
"script": {
@@ -2444,6 +2464,16 @@
{
"name": "Payments - Create",
"event": [
+ {
+ "listen": "prerequest",
+ "script": {
+ "exec": [
+ "pm.environment.set(\"random_number\", _.random(1000, 100000));",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ },
{
"listen": "test",
"script": {
@@ -3583,6 +3613,16 @@
{
"name": "Payments - Create",
"event": [
+ {
+ "listen": "prerequest",
+ "script": {
+ "exec": [
+ "pm.environment.set(\"random_number\", _.random(1000, 100000));",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ },
{
"listen": "test",
"script": {
diff --git a/postman/collection-json/checkout.postman_collection.json b/postman/collection-json/checkout.postman_collection.json
index 0a1afbdd04a..cdb94b4a84b 100644
--- a/postman/collection-json/checkout.postman_collection.json
+++ b/postman/collection-json/checkout.postman_collection.json
@@ -899,6 +899,16 @@
{
"name": "Payments - Create",
"event": [
+ {
+ "listen": "prerequest",
+ "script": {
+ "exec": [
+ "pm.environment.set(\"random_number\", _.random(1000, 100000));",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ },
{
"listen": "test",
"script": {
@@ -1906,6 +1916,16 @@
{
"name": "Payments - Create",
"event": [
+ {
+ "listen": "prerequest",
+ "script": {
+ "exec": [
+ "pm.environment.set(\"random_number\", _.random(1000, 100000));",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ },
{
"listen": "test",
"script": {
@@ -2532,6 +2552,16 @@
{
"name": "Payments - Create",
"event": [
+ {
+ "listen": "prerequest",
+ "script": {
+ "exec": [
+ "pm.environment.set(\"random_number\", _.random(1000, 100000));",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ },
{
"listen": "test",
"script": {
@@ -3176,6 +3206,16 @@
{
"name": "Payments - Create",
"event": [
+ {
+ "listen": "prerequest",
+ "script": {
+ "exec": [
+ "pm.environment.set(\"random_number\", _.random(1000, 100000));",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ },
{
"listen": "test",
"script": {
diff --git a/postman/collection-json/nmi.postman_collection.json b/postman/collection-json/nmi.postman_collection.json
index d25030fad27..fa1dbac954f 100644
--- a/postman/collection-json/nmi.postman_collection.json
+++ b/postman/collection-json/nmi.postman_collection.json
@@ -815,7 +815,7 @@
"name": "Happy Cases",
"item": [
{
- "name": "Scenario10-Create a mandate and recurring payment",
+ "name": "Scenario1-Create payment with confirm true",
"item": [
{
"name": "Payments - Create",
@@ -824,7 +824,7 @@
"listen": "prerequest",
"script": {
"exec": [
- "pm.environment.set(\"random_number\", _.random(100, 100000));",
+ "pm.environment.set(\"random_number\", _.random(1000, 100000));",
""
],
"type": "text/javascript"
@@ -896,7 +896,7 @@
" );",
"}",
"",
- "// Response body should have value \"processing\" for \"status\"",
+ "// Response body should have value \"succeeded\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
" \"[POST]::/payments - Content check if value for 'status' matches 'processing'\",",
@@ -905,22 +905,6 @@
" },",
" );",
"}",
- "",
- "// Response body should have \"mandate_id\"",
- "pm.test(",
- " \"[POST]::/payments - Content check if 'mandate_id' exists\",",
- " function () {",
- " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;",
- " },",
- ");",
- "",
- "// Response body should have \"mandate_data\"",
- "pm.test(",
- " \"[POST]::/payments - Content check if 'mandate_data' exists\",",
- " function () {",
- " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;",
- " },",
- ");",
""
],
"type": "text/javascript"
@@ -946,7 +930,7 @@
"language": "json"
}
},
- "raw": "{\"amount\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"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://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4111111111111111\",\"card_exp_month\":\"10\",\"card_exp_year\":\"69\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"setup_future_usage\":\"off_session\",\"mandate_data\":{\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"127.0.0.1\",\"user_agent\":\"amet irure esse\"}},\"mandate_type\":{\"single_use\":{\"amount\":100000,\"currency\":\"USD\"}}},\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"127.0.0.1\",\"user_agent\":\"amet irure esse\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
+ "raw": "{\"amount\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"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://duck.com\",\"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\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
},
"url": {
"raw": "{{baseUrl}}/payments",
@@ -1039,22 +1023,6 @@
" },",
" );",
"}",
- "",
- "// Response body should have \"mandate_id\"",
- "pm.test(",
- " \"[POST]::/payments - Content check if 'mandate_id' exists\",",
- " function () {",
- " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;",
- " },",
- ");",
- "",
- "// Response body should have \"mandate_data\"",
- "pm.test(",
- " \"[POST]::/payments - Content check if 'mandate_data' exists\",",
- " function () {",
- " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;",
- " },",
- ");",
""
],
"type": "text/javascript"
@@ -1095,15 +1063,20 @@
"description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
},
"response": []
- },
+ }
+ ]
+ },
+ {
+ "name": "Scenario2-Create payment with confirm false",
+ "item": [
{
- "name": "Recurring Payments - Create",
+ "name": "Payments - Create",
"event": [
{
"listen": "prerequest",
"script": {
"exec": [
- "pm.environment.set(\"random_number\", _.random(100, 100000));",
+ "pm.environment.set(\"random_number\", _.random(1000, 100000));",
""
],
"type": "text/javascript"
@@ -1175,39 +1148,136 @@
" );",
"}",
"",
- "// Response body should have value \"processing\" for \"status\"",
+ "// Response body should have value \"requires_confirmation\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments - Content check if value for 'status' matches 'processing'\",",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'requires_confirmation'\",",
" function () {",
- " pm.expect(jsonData.status).to.eql(\"processing\");",
+ " pm.expect(jsonData.status).to.eql(\"requires_confirmation\");",
" },",
" );",
"}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my last payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"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\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Confirm",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments/:id/confirm - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
"",
- "// Response body should have \"mandate_id\"",
+ "// Validate if response header has matching content-type",
"pm.test(",
- " \"[POST]::/payments - Content check if 'mandate_id' exists\",",
+ " \"[POST]::/payments/:id/confirm - Content-Type is application/json\",",
" function () {",
- " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
" },",
");",
"",
- "// Response body should have \"mandate_data\"",
- "pm.test(",
- " \"[POST]::/payments - Content check if 'mandate_data' exists\",",
- " function () {",
- " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;",
- " },",
- ");",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
"",
- "// Response body should have \"payment_method_data\"",
- "pm.test(",
- " \"[POST]::/payments - Content check if 'payment_method_data' exists\",",
- " function () {",
- " pm.expect(typeof jsonData.payment_method_data !== \"undefined\").to.be.true;",
- " },",
- ");",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
+ "if (jsonData?.mandate_id) {",
+ " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ " console.log(",
+ " \"- use {{mandate_id}} as collection variable for value\",",
+ " jsonData.mandate_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'processing'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"processing\");",
+ " },",
+ " );",
+ "}",
""
],
"type": "text/javascript"
@@ -1215,6 +1285,26 @@
}
],
"request": {
+ "auth": {
+ "type": "apikey",
+ "apikey": [
+ {
+ "key": "value",
+ "value": "{{publishable_key}}",
+ "type": "string"
+ },
+ {
+ "key": "key",
+ "value": "api-key",
+ "type": "string"
+ },
+ {
+ "key": "in",
+ "value": "header",
+ "type": "string"
+ }
+ ]
+ },
"method": "POST",
"header": [
{
@@ -1233,23 +1323,32 @@
"language": "json"
}
},
- "raw": "{\"amount\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"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://duck.com\",\"mandate_id\":\"{{mandate_id}}\",\"off_session\":true,\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
+ "raw": "{\"client_secret\":\"{{client_secret}}\"}"
},
"url": {
- "raw": "{{baseUrl}}/payments",
+ "raw": "{{baseUrl}}/payments/:id/confirm",
"host": [
"{{baseUrl}}"
],
"path": [
- "payments"
+ "payments",
+ ":id",
+ "confirm"
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
]
},
- "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API"
},
"response": []
},
{
- "name": "Payments - Retrieve-copy",
+ "name": "Payments - Retrieve",
"event": [
{
"listen": "test",
@@ -1317,31 +1416,15 @@
" );",
"}",
"",
- "// Response body should have value \"Succeeded\" for \"status\"",
+ "// Response body should have value \"succeeded\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",",
+ " \"[POST]::/payments:id - Content check if value for 'status' matches 'succeeded'\",",
" function () {",
" pm.expect(jsonData.status).to.eql(\"succeeded\");",
" },",
" );",
"}",
- "",
- "// Response body should have \"mandate_id\"",
- "pm.test(",
- " \"[POST]::/payments - Content check if 'mandate_id' exists\",",
- " function () {",
- " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;",
- " },",
- ");",
- "",
- "// Response body should have \"mandate_data\"",
- "pm.test(",
- " \"[POST]::/payments - Content check if 'mandate_data' exists\",",
- " function () {",
- " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;",
- " },",
- ");",
""
],
"type": "text/javascript"
@@ -1386,7 +1469,7 @@
]
},
{
- "name": "Scenario11-Refund recurring payment",
+ "name": "Scenario2a-Create payment with confirm false card holder name null",
"item": [
{
"name": "Payments - Create",
@@ -1395,7 +1478,7 @@
"listen": "prerequest",
"script": {
"exec": [
- "pm.environment.set(\"random_number\", _.random(100, 100000));",
+ "pm.environment.set(\"random_number\", _.random(1000, 100000));",
""
],
"type": "text/javascript"
@@ -1405,9 +1488,6 @@
"listen": "test",
"script": {
"exec": [
- "// Set the environment variable 'amount' with the value from the response",
- "pm.environment.set(\"amount\", pm.response.json().amount);",
- "",
"// Validate status 2xx",
"pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
" pm.response.to.be.success;",
@@ -1470,31 +1550,15 @@
" );",
"}",
"",
- "// Response body should have value \"processing\" for \"status\"",
+ "// Response body should have value \"requires_payment_method\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments - Content check if value for 'status' matches 'processing'\",",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'\",",
" function () {",
- " pm.expect(jsonData.status).to.eql(\"processing\");",
+ " pm.expect(jsonData.status).to.eql(\"requires_payment_method\");",
" },",
" );",
"}",
- "",
- "// Response body should have \"mandate_id\"",
- "pm.test(",
- " \"[POST]::/payments - Content check if 'mandate_id' exists\",",
- " function () {",
- " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;",
- " },",
- ");",
- "",
- "// Response body should have \"mandate_data\"",
- "pm.test(",
- " \"[POST]::/payments - Content check if 'mandate_data' exists\",",
- " function () {",
- " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;",
- " },",
- ");",
""
],
"type": "text/javascript"
@@ -1520,7 +1584,7 @@
"language": "json"
}
},
- "raw": "{\"amount\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"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://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4111111111111111\",\"card_exp_month\":\"10\",\"card_exp_year\":\"69\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"setup_future_usage\":\"off_session\",\"mandate_data\":{\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"127.0.0.1\",\"user_agent\":\"amet irure esse\"}},\"mandate_type\":{\"single_use\":{\"amount\":100000,\"currency\":\"USD\"}}},\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"127.0.0.1\",\"user_agent\":\"amet irure esse\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
+ "raw": "{\"amount\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"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://duck.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
},
"url": {
"raw": "{{baseUrl}}/payments",
@@ -1536,26 +1600,38 @@
"response": []
},
{
- "name": "Payments - Retrieve",
+ "name": "Payments - Confirm",
"event": [
+ {
+ "listen": "prerequest",
+ "script": {
+ "exec": [
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ },
{
"listen": "test",
"script": {
"exec": [
"// Validate status 2xx",
- "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
+ "pm.test(\"[POST]::/payments/:id/confirm - Status code is 2xx\", function () {",
" pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
- "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
- " \"application/json\",",
- " );",
- "});",
+ "pm.test(",
+ " \"[POST]::/payments/:id/confirm - 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(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
+ "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {",
" pm.response.to.have.jsonBody();",
"});",
"",
@@ -1604,31 +1680,15 @@
" );",
"}",
"",
- "// Response body should have value \"Succeeded\" for \"status\"",
+ "// Response body should have value \"processing\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",",
+ " \"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'processing'\",",
" function () {",
- " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " pm.expect(jsonData.status).to.eql(\"processing\");",
" },",
" );",
"}",
- "",
- "// Response body should have \"mandate_id\"",
- "pm.test(",
- " \"[POST]::/payments - Content check if 'mandate_id' exists\",",
- " function () {",
- " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;",
- " },",
- ");",
- "",
- "// Response body should have \"mandate_data\"",
- "pm.test(",
- " \"[POST]::/payments - Content check if 'mandate_data' exists\",",
- " function () {",
- " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;",
- " },",
- ");",
""
],
"type": "text/javascript"
@@ -1636,27 +1696,55 @@
}
],
"request": {
- "method": "GET",
+ "auth": {
+ "type": "apikey",
+ "apikey": [
+ {
+ "key": "value",
+ "value": "{{publishable_key}}",
+ "type": "string"
+ },
+ {
+ "key": "key",
+ "value": "api-key",
+ "type": "string"
+ },
+ {
+ "key": "in",
+ "value": "header",
+ "type": "string"
+ }
+ ]
+ },
+ "method": "POST",
"header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
{
"key": "Accept",
"value": "application/json"
}
],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4111111111111111\",\"card_exp_month\":\"10\",\"card_exp_year\":\"69\",\"card_holder_name\":null,\"card_cvc\":\"123\"}},\"client_secret\":\"{{client_secret}}\",\"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\":\"125.0.0.1\"}}"
+ },
"url": {
- "raw": "{{baseUrl}}/payments/:id?force_sync=true",
+ "raw": "{{baseUrl}}/payments/:id/confirm",
"host": [
"{{baseUrl}}"
],
"path": [
"payments",
- ":id"
- ],
- "query": [
- {
- "key": "force_sync",
- "value": "true"
- }
+ ":id",
+ "confirm"
],
"variable": [
{
@@ -1666,44 +1754,31 @@
}
]
},
- "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API"
},
"response": []
},
{
- "name": "Recurring Payments - Create",
+ "name": "Payments - Retrieve",
"event": [
- {
- "listen": "prerequest",
- "script": {
- "exec": [
- "pm.environment.set(\"random_number\", _.random(100, 100000));",
- ""
- ],
- "type": "text/javascript"
- }
- },
{
"listen": "test",
"script": {
"exec": [
- "// Set the environment variable 'amount' with the value from the response",
- "pm.environment.set(\"amount\", pm.response.json().amount);",
- "",
"// Validate status 2xx",
- "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
" pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
- "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ "pm.test(\"[GET]::/payments/:id - 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]::/payments - Response has JSON Body\", function () {",
+ "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
" pm.response.to.have.jsonBody();",
"});",
"",
@@ -1752,39 +1827,15 @@
" );",
"}",
"",
- "// Response body should have value \"processing\" for \"status\"",
+ "// Response body should have value \"succeeded\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments - Content check if value for 'status' matches 'processing'\",",
+ " \"[POST]::/payments:id - Content check if value for 'status' matches 'succeeded'\",",
" function () {",
- " pm.expect(jsonData.status).to.eql(\"processing\");",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
" },",
" );",
"}",
- "",
- "// Response body should have \"mandate_id\"",
- "pm.test(",
- " \"[POST]::/payments - Content check if 'mandate_id' exists\",",
- " function () {",
- " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;",
- " },",
- ");",
- "",
- "// Response body should have \"mandate_data\"",
- "pm.test(",
- " \"[POST]::/payments - Content check if 'mandate_data' exists\",",
- " function () {",
- " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;",
- " },",
- ");",
- "",
- "// Response body should have \"payment_method_data\"",
- "pm.test(",
- " \"[POST]::/payments - Content check if 'payment_method_data' exists\",",
- " function () {",
- " pm.expect(typeof jsonData.payment_method_data !== \"undefined\").to.be.true;",
- " },",
- ");",
""
],
"type": "text/javascript"
@@ -1792,60 +1843,76 @@
}
],
"request": {
- "method": "POST",
+ "method": "GET",
"header": [
- {
- "key": "Content-Type",
- "value": "application/json"
- },
{
"key": "Accept",
"value": "application/json"
}
],
- "body": {
- "mode": "raw",
- "options": {
- "raw": {
- "language": "json"
- }
- },
- "raw": "{\"amount\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"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://duck.com\",\"mandate_id\":\"{{mandate_id}}\",\"off_session\":true,\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
- },
"url": {
- "raw": "{{baseUrl}}/payments",
+ "raw": "{{baseUrl}}/payments/:id?force_sync=true",
"host": [
"{{baseUrl}}"
],
"path": [
- "payments"
+ "payments",
+ ":id"
+ ],
+ "query": [
+ {
+ "key": "force_sync",
+ "value": "true"
+ }
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
]
},
- "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
},
"response": []
- },
+ }
+ ]
+ },
+ {
+ "name": "Scenario2b-Create payment with confirm false card holder name empty",
+ "item": [
{
- "name": "Payments - Retrieve-copy",
+ "name": "Payments - Create",
"event": [
+ {
+ "listen": "prerequest",
+ "script": {
+ "exec": [
+ "pm.environment.set(\"random_number\", _.random(1000, 100000));",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ },
{
"listen": "test",
"script": {
"exec": [
"// Validate status 2xx",
- "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
" pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
- "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {",
+ "pm.test(\"[POST]::/payments - 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(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
" pm.response.to.have.jsonBody();",
"});",
"",
@@ -1894,31 +1961,15 @@
" );",
"}",
"",
- "// Response body should have value \"Succeeded\" for \"status\"",
+ "// Response body should have value \"requires_payment_method\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'\",",
" function () {",
- " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " pm.expect(jsonData.status).to.eql(\"requires_payment_method\");",
" },",
" );",
"}",
- "",
- "// Response body should have \"mandate_id\"",
- "pm.test(",
- " \"[POST]::/payments - Content check if 'mandate_id' exists\",",
- " function () {",
- " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;",
- " },",
- ");",
- "",
- "// Response body should have \"mandate_data\"",
- "pm.test(",
- " \"[POST]::/payments - Content check if 'mandate_data' exists\",",
- " function () {",
- " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;",
- " },",
- ");",
""
],
"type": "text/javascript"
@@ -1926,42 +1977,41 @@
}
],
"request": {
- "method": "GET",
+ "method": "POST",
"header": [
{
- "key": "Accept",
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
"value": "application/json"
}
],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"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://duck.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
+ },
"url": {
- "raw": "{{baseUrl}}/payments/:id?force_sync=true",
+ "raw": "{{baseUrl}}/payments",
"host": [
"{{baseUrl}}"
],
"path": [
- "payments",
- ":id"
- ],
- "query": [
- {
- "key": "force_sync",
- "value": "true"
- }
- ],
- "variable": [
- {
- "key": "id",
- "value": "{{payment_id}}",
- "description": "(Required) unique payment id"
- }
+ "payments"
]
},
- "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
},
"response": []
},
{
- "name": "Refunds - Create",
+ "name": "Payments - Confirm",
"event": [
{
"listen": "prerequest",
@@ -1976,19 +2026,24 @@
"listen": "test",
"script": {
"exec": [
- "// Get the value of 'amount' from the environment",
- "const amount = pm.environment.get(\"amount\");",
- "",
"// Validate status 2xx",
- "pm.test(\"[POST]::/refunds - Status code is 2xx\", function () {",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
" pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
- "pm.test(\"[POST]::/refunds - Content-Type is application/json\", function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
- " \"application/json\",",
- " );",
+ "pm.test(",
+ " \"[POST]::/payments/:id/confirm - 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]::/payments/:id/confirm - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
"});",
"",
"// Set response object as internal variable",
@@ -1997,45 +2052,80 @@
" jsonData = pm.response.json();",
"} catch (e) {}",
"",
- "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id",
- "if (jsonData?.refund_id) {",
- " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
" console.log(",
- " \"- use {{refund_id}} as collection variable for value\",",
- " jsonData.refund_id,",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
" );",
"} else {",
" console.log(",
- " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
" );",
"}",
"",
- "// Response body should have value \"pending\" for \"status\"",
- "if (jsonData?.status) {",
- " pm.test(",
- " \"[POST]::/refunds - Content check if value for 'status' matches 'pending'\",",
- " function () {",
- " pm.expect(jsonData.status).to.eql(\"pending\");",
- " },",
+ "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
+ "if (jsonData?.mandate_id) {",
+ " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ " console.log(",
+ " \"- use {{mandate_id}} as collection variable for value\",",
+ " jsonData.mandate_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
" );",
"}",
"",
- "// Response body should have value for \"amount\"",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"processing\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/refunds - Content check if value for 'amount' matches '{{amount}}'\",",
+ " \"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'processing'\",",
" function () {",
- " pm.expect(jsonData.amount).to.eql(amount);",
+ " pm.expect(jsonData.status).to.eql(\"processing\");",
" },",
" );",
- "}",
- ""
+ "}"
],
"type": "text/javascript"
}
}
],
"request": {
+ "auth": {
+ "type": "apikey",
+ "apikey": [
+ {
+ "key": "value",
+ "value": "{{publishable_key}}",
+ "type": "string"
+ },
+ {
+ "key": "key",
+ "value": "api-key",
+ "type": "string"
+ },
+ {
+ "key": "in",
+ "value": "header",
+ "type": "string"
+ }
+ ]
+ },
"method": "POST",
"header": [
{
@@ -2054,91 +2144,108 @@
"language": "json"
}
},
- "raw": "{\"payment_id\":\"{{payment_id}}\",\"amount\":\"{{amount}}\",\"reason\":\"Customer returned product\",\"refund_type\":\"instant\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
+ "raw": "{\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4111111111111111\",\"card_exp_month\":\"10\",\"card_exp_year\":\"69\",\"card_holder_name\":\"\",\"card_cvc\":\"123\"}},\"client_secret\":\"{{client_secret}}\",\"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\":\"125.0.0.1\"}}"
},
"url": {
- "raw": "{{baseUrl}}/refunds",
+ "raw": "{{baseUrl}}/payments/:id/confirm",
"host": [
"{{baseUrl}}"
],
"path": [
- "refunds"
+ "payments",
+ ":id",
+ "confirm"
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
]
},
- "description": "To create a refund against an already processed payment"
+ "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API"
},
"response": []
},
{
- "name": "Refunds - Retrieve",
+ "name": "Payments - Retrieve",
"event": [
- {
- "listen": "prerequest",
- "script": {
- "exec": [
- ""
- ],
- "type": "text/javascript"
- }
- },
{
"listen": "test",
"script": {
"exec": [
- "// Get the value of 'amount' from the environment",
- "const refund_amount = pm.environment.get(\"amount\");",
- "",
"// Validate status 2xx",
- "pm.test(\"[GET]::/refunds/:id - Status code is 2xx\", function () {",
+ "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
" pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
- "pm.test(\"[GET]::/refunds/:id - Content-Type is application/json\", function () {",
+ "pm.test(\"[GET]::/payments/:id - 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(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
"// Set response object as internal variable",
"let jsonData = {};",
"try {",
" jsonData = pm.response.json();",
"} catch (e) {}",
"",
- "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id",
- "if (jsonData?.refund_id) {",
- " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
" console.log(",
- " \"- use {{refund_id}} as collection variable for value\",",
- " jsonData.refund_id,",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
" );",
"} else {",
" console.log(",
- " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
" );",
"}",
"",
- "// Response body should have value \"succeeded\" for \"status\"",
- "if (jsonData?.status) {",
- " pm.test(",
- " \"[POST]::/refunds - Content check if value for 'status' matches 'succeeded'\",",
- " function () {",
- " pm.expect(jsonData.status).to.eql(\"succeeded\");",
- " },",
+ "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
+ "if (jsonData?.mandate_id) {",
+ " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ " console.log(",
+ " \"- use {{mandate_id}} as collection variable for value\",",
+ " jsonData.mandate_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
" );",
"}",
"",
- "// Response body should have value for \"refund_amount\"",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"succeeded\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/refunds - Content check if value for 'refund_amount' matches '{{refund_amount}}'\",",
+ " \"[POST]::/payments:id - Content check if value for 'status' matches 'succeeded'\",",
" function () {",
- " pm.expect(jsonData.amount).to.eql(refund_amount);",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
" },",
" );",
- "}",
- ""
+ "}"
],
"type": "text/javascript"
}
@@ -2153,30 +2260,36 @@
}
],
"url": {
- "raw": "{{baseUrl}}/refunds/:id",
+ "raw": "{{baseUrl}}/payments/:id?force_sync=true",
"host": [
"{{baseUrl}}"
],
"path": [
- "refunds",
+ "payments",
":id"
],
+ "query": [
+ {
+ "key": "force_sync",
+ "value": "true"
+ }
+ ],
"variable": [
{
"key": "id",
- "value": "{{refund_id}}",
- "description": "(Required) unique refund id"
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
}
]
},
- "description": "To retrieve the properties of a Refund. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
},
"response": []
}
]
},
{
- "name": "Scenario1-Create payment with confirm true",
+ "name": "Scenario3-Create payment without PMD",
"item": [
{
"name": "Payments - Create",
@@ -2257,12 +2370,12 @@
" );",
"}",
"",
- "// Response body should have value \"succeeded\" for \"status\"",
+ "// Response body should have value \"requires_payment_method\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments - Content check if value for 'status' matches 'processing'\",",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'\",",
" function () {",
- " pm.expect(jsonData.status).to.eql(\"processing\");",
+ " pm.expect(jsonData.status).to.eql(\"requires_payment_method\");",
" },",
" );",
"}",
@@ -2291,7 +2404,7 @@
"language": "json"
}
},
- "raw": "{\"amount\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"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://duck.com\",\"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\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
+ "raw": "{\"amount\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"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://duck.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
},
"url": {
"raw": "{{baseUrl}}/payments",
@@ -2307,26 +2420,38 @@
"response": []
},
{
- "name": "Payments - Retrieve",
+ "name": "Payments - Confirm",
"event": [
+ {
+ "listen": "prerequest",
+ "script": {
+ "exec": [
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ },
{
"listen": "test",
"script": {
"exec": [
"// Validate status 2xx",
- "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
+ "pm.test(\"[POST]::/payments/:id/confirm - Status code is 2xx\", function () {",
" pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
- "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
- " \"application/json\",",
- " );",
- "});",
+ "pm.test(",
+ " \"[POST]::/payments/:id/confirm - 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(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
+ "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {",
" pm.response.to.have.jsonBody();",
"});",
"",
@@ -2375,12 +2500,12 @@
" );",
"}",
"",
- "// Response body should have value \"Succeeded\" for \"status\"",
+ "// Response body should have value \"succeeded\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",",
+ " \"[POST]::/payments:id/confirm - Content check if value for 'status' matches 'processing'\",",
" function () {",
- " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " pm.expect(jsonData.status).to.eql(\"processing\");",
" },",
" );",
"}",
@@ -2391,27 +2516,55 @@
}
],
"request": {
- "method": "GET",
+ "auth": {
+ "type": "apikey",
+ "apikey": [
+ {
+ "key": "value",
+ "value": "{{publishable_key}}",
+ "type": "string"
+ },
+ {
+ "key": "key",
+ "value": "api-key",
+ "type": "string"
+ },
+ {
+ "key": "in",
+ "value": "header",
+ "type": "string"
+ }
+ ]
+ },
+ "method": "POST",
"header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
{
"key": "Accept",
"value": "application/json"
}
],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"client_secret\":\"{{client_secret}}\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4111111111111111\",\"card_exp_month\":\"10\",\"card_exp_year\":\"69\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}}}"
+ },
"url": {
- "raw": "{{baseUrl}}/payments/:id?force_sync=true",
+ "raw": "{{baseUrl}}/payments/:id/confirm",
"host": [
"{{baseUrl}}"
],
"path": [
"payments",
- ":id"
- ],
- "query": [
- {
- "key": "force_sync",
- "value": "true"
- }
+ ":id",
+ "confirm"
],
"variable": [
{
@@ -2421,46 +2574,31 @@
}
]
},
- "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API"
},
"response": []
- }
- ]
- },
- {
- "name": "Scenario2-Create payment with confirm false",
- "item": [
+ },
{
- "name": "Payments - Create",
+ "name": "Payments - Retrieve",
"event": [
- {
- "listen": "prerequest",
- "script": {
- "exec": [
- "pm.environment.set(\"random_number\", _.random(1000, 100000));",
- ""
- ],
- "type": "text/javascript"
- }
- },
{
"listen": "test",
"script": {
"exec": [
"// Validate status 2xx",
- "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
" pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
- "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ "pm.test(\"[GET]::/payments/:id - 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]::/payments - Response has JSON Body\", function () {",
+ "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
" pm.response.to.have.jsonBody();",
"});",
"",
@@ -2509,12 +2647,12 @@
" );",
"}",
"",
- "// Response body should have value \"requires_confirmation\" for \"status\"",
+ "// Response body should have value \"succeeded\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments - Content check if value for 'status' matches 'requires_confirmation'\",",
+ " \"[POST]::/payments:id - Content check if value for 'status' matches 'succeeded'\",",
" function () {",
- " pm.expect(jsonData.status).to.eql(\"requires_confirmation\");",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
" },",
" );",
"}",
@@ -2525,63 +2663,78 @@
}
],
"request": {
- "method": "POST",
+ "method": "GET",
"header": [
- {
- "key": "Content-Type",
- "value": "application/json"
- },
{
"key": "Accept",
"value": "application/json"
}
],
- "body": {
- "mode": "raw",
- "options": {
- "raw": {
- "language": "json"
- }
- },
- "raw": "{\"amount\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"customer_id\":\"StripeCustomer\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my last payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"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\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
- },
"url": {
- "raw": "{{baseUrl}}/payments",
+ "raw": "{{baseUrl}}/payments/:id?force_sync=true",
"host": [
"{{baseUrl}}"
],
"path": [
- "payments"
+ "payments",
+ ":id"
+ ],
+ "query": [
+ {
+ "key": "force_sync",
+ "value": "true"
+ }
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
]
},
- "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
},
"response": []
- },
+ }
+ ]
+ },
+ {
+ "name": "Scenario4-Create payment with Manual capture",
+ "item": [
{
- "name": "Payments - Confirm",
+ "name": "Payments - Create",
"event": [
+ {
+ "listen": "prerequest",
+ "script": {
+ "exec": [
+ "pm.environment.set(\"random_number\", _.random(1000, 100000));",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ },
{
"listen": "test",
"script": {
"exec": [
+ "pm.environment.set(\"amount\", pm.response.json().amount);",
+ "",
"// Validate status 2xx",
- "pm.test(\"[POST]::/payments/:id/confirm - Status code is 2xx\", function () {",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
" pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
- "pm.test(",
- " \"[POST]::/payments/:id/confirm - Content-Type is application/json\",",
- " function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
- " \"application/json\",",
- " );",
- " },",
- ");",
+ "pm.test(\"[POST]::/payments - 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]::/payments/:id/confirm - Response has JSON Body\", function () {",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
" pm.response.to.have.jsonBody();",
"});",
"",
@@ -2630,10 +2783,10 @@
" );",
"}",
"",
- "// Response body should have value \"succeeded\" for \"status\"",
+ "// Response body should have value \"requires_capture\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'processing'\",",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'processing'\",",
" function () {",
" pm.expect(jsonData.status).to.eql(\"processing\");",
" },",
@@ -2646,26 +2799,6 @@
}
],
"request": {
- "auth": {
- "type": "apikey",
- "apikey": [
- {
- "key": "value",
- "value": "{{publishable_key}}",
- "type": "string"
- },
- {
- "key": "key",
- "value": "api-key",
- "type": "string"
- },
- {
- "key": "in",
- "value": "header",
- "type": "string"
- }
- ]
- },
"method": "POST",
"header": [
{
@@ -2684,27 +2817,18 @@
"language": "json"
}
},
- "raw": "{\"client_secret\":\"{{client_secret}}\"}"
+ "raw": "{\"amount\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"manual\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"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://duck.com\",\"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\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
},
"url": {
- "raw": "{{baseUrl}}/payments/:id/confirm",
+ "raw": "{{baseUrl}}/payments",
"host": [
"{{baseUrl}}"
],
"path": [
- "payments",
- ":id",
- "confirm"
- ],
- "variable": [
- {
- "key": "id",
- "value": "{{payment_id}}",
- "description": "(Required) unique payment id"
- }
+ "payments"
]
},
- "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API"
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
},
"response": []
},
@@ -2780,9 +2904,9 @@
"// Response body should have value \"succeeded\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments:id - Content check if value for 'status' matches 'succeeded'\",",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'requires_capture'\",",
" function () {",
- " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " pm.expect(jsonData.status).to.eql(\"requires_capture\");",
" },",
" );",
"}",
@@ -2826,20 +2950,14 @@
"description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
},
"response": []
- }
- ]
- },
- {
- "name": "Scenario2a-Create payment with confirm false card holder name null",
- "item": [
+ },
{
- "name": "Payments - Create",
+ "name": "Payments - Capture",
"event": [
{
"listen": "prerequest",
"script": {
"exec": [
- "pm.environment.set(\"random_number\", _.random(1000, 100000));",
""
],
"type": "text/javascript"
@@ -2849,20 +2967,26 @@
"listen": "test",
"script": {
"exec": [
+ "// Get the value of 'amount' from the environment",
+ "const amount = pm.environment.get(\"amount\");",
+ "",
"// Validate status 2xx",
- "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ "pm.test(\"[POST]::/payments/:id/capture - Status code is 2xx\", function () {",
" pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
- "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
- " \"application/json\",",
- " );",
- "});",
+ "pm.test(",
+ " \"[POST]::/payments/:id/capture - 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]::/payments - Response has JSON Body\", function () {",
+ "pm.test(\"[POST]::/payments/:id/capture - Response has JSON Body\", function () {",
" pm.response.to.have.jsonBody();",
"});",
"",
@@ -2911,142 +3035,32 @@
" );",
"}",
"",
- "// Response body should have value \"requires_payment_method\" for \"status\"",
+ "// Response body should have value \"succeeded\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'\",",
+ " \"[POST]:://payments/:id/capture - Content check if value for 'status' matches 'processing'\",",
" function () {",
- " pm.expect(jsonData.status).to.eql(\"requires_payment_method\");",
+ " pm.expect(jsonData.status).to.eql(\"processing\");",
" },",
" );",
"}",
- ""
- ],
- "type": "text/javascript"
- }
- }
- ],
- "request": {
- "method": "POST",
- "header": [
- {
- "key": "Content-Type",
- "value": "application/json"
- },
- {
- "key": "Accept",
- "value": "application/json"
- }
- ],
- "body": {
- "mode": "raw",
- "options": {
- "raw": {
- "language": "json"
- }
- },
- "raw": "{\"amount\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"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://duck.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
- },
- "url": {
- "raw": "{{baseUrl}}/payments",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments"
- ]
- },
- "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
- },
- "response": []
- },
- {
- "name": "Payments - Confirm",
- "event": [
- {
- "listen": "prerequest",
- "script": {
- "exec": [
- ""
- ],
- "type": "text/javascript"
- }
- },
- {
- "listen": "test",
- "script": {
- "exec": [
- "// Validate status 2xx",
- "pm.test(\"[POST]::/payments/:id/confirm - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
- "});",
- "",
- "// Validate if response header has matching content-type",
- "pm.test(",
- " \"[POST]::/payments/:id/confirm - 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]::/payments/:id/confirm - Response has JSON Body\", function () {",
- " pm.response.to.have.jsonBody();",
- "});",
- "",
- "// Set response object as internal variable",
- "let jsonData = {};",
- "try {",
- " jsonData = pm.response.json();",
- "} catch (e) {}",
- "",
- "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
- "if (jsonData?.payment_id) {",
- " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
- " console.log(",
- " \"- use {{payment_id}} as collection variable for value\",",
- " jsonData.payment_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
- " );",
- "}",
- "",
- "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
- "if (jsonData?.mandate_id) {",
- " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
- " console.log(",
- " \"- use {{mandate_id}} as collection variable for value\",",
- " jsonData.mandate_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
- " );",
- "}",
"",
- "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
- "if (jsonData?.client_secret) {",
- " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
- " console.log(",
- " \"- use {{client_secret}} as collection variable for value\",",
- " jsonData.client_secret,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ "// Response body should have value \"{{amount}}\" for \"amount\"",
+ "if (jsonData?.amount) {",
+ " pm.test(",
+ " \"[post]:://payments/:id/capture - Content check if value for 'amount' matches '{{amount}}'\",",
+ " function () {",
+ " pm.expect(jsonData.amount).to.eql(amount);",
+ " },",
" );",
"}",
"",
- "// Response body should have value \"processing\" for \"status\"",
- "if (jsonData?.status) {",
+ "// Response body should have value \"{{amount}}\" for \"amount_received\"",
+ "if (jsonData?.amount_received) {",
" pm.test(",
- " \"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'processing'\",",
+ " \"[POST]::/payments:id/capture - Content check if value for 'amount_received' matches '{{amount}}'\",",
" function () {",
- " pm.expect(jsonData.status).to.eql(\"processing\");",
+ " pm.expect(jsonData.amount_received).to.eql(amount);",
" },",
" );",
"}",
@@ -3057,26 +3071,6 @@
}
],
"request": {
- "auth": {
- "type": "apikey",
- "apikey": [
- {
- "key": "value",
- "value": "{{publishable_key}}",
- "type": "string"
- },
- {
- "key": "key",
- "value": "api-key",
- "type": "string"
- },
- {
- "key": "in",
- "value": "header",
- "type": "string"
- }
- ]
- },
"method": "POST",
"header": [
{
@@ -3095,17 +3089,17 @@
"language": "json"
}
},
- "raw": "{\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4111111111111111\",\"card_exp_month\":\"10\",\"card_exp_year\":\"69\",\"card_holder_name\":null,\"card_cvc\":\"123\"}},\"client_secret\":\"{{client_secret}}\",\"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\":\"125.0.0.1\"}}"
+ "raw": "{\"amount_to_capture\":\"{{amount}}\",\"statement_descriptor_name\":\"Joseph\",\"statement_descriptor_suffix\":\"JS\"}"
},
"url": {
- "raw": "{{baseUrl}}/payments/:id/confirm",
+ "raw": "{{baseUrl}}/payments/:id/capture",
"host": [
"{{baseUrl}}"
],
"path": [
"payments",
":id",
- "confirm"
+ "capture"
],
"variable": [
{
@@ -3115,12 +3109,12 @@
}
]
},
- "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API"
+ "description": "To capture the funds for an uncaptured payment"
},
"response": []
},
{
- "name": "Payments - Retrieve",
+ "name": "Payments - Retrieve-copy",
"event": [
{
"listen": "test",
@@ -3191,7 +3185,7 @@
"// Response body should have value \"succeeded\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments:id - Content check if value for 'status' matches 'succeeded'\",",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",",
" function () {",
" pm.expect(jsonData.status).to.eql(\"succeeded\");",
" },",
@@ -3241,7 +3235,7 @@
]
},
{
- "name": "Scenario2b-Create payment with confirm false card holder name empty",
+ "name": "Scenario5-Void the payment",
"item": [
{
"name": "Payments - Create",
@@ -3322,12 +3316,12 @@
" );",
"}",
"",
- "// Response body should have value \"requires_payment_method\" for \"status\"",
+ "// Response body should have value \"requires_capture\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'\",",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'processing'\",",
" function () {",
- " pm.expect(jsonData.status).to.eql(\"requires_payment_method\");",
+ " pm.expect(jsonData.status).to.eql(\"processing\");",
" },",
" );",
"}",
@@ -3356,7 +3350,7 @@
"language": "json"
}
},
- "raw": "{\"amount\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"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://duck.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
+ "raw": "{\"amount\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"manual\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"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://duck.com\",\"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\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
},
"url": {
"raw": "{{baseUrl}}/payments",
@@ -3372,38 +3366,26 @@
"response": []
},
{
- "name": "Payments - Confirm",
+ "name": "Payments - Retrieve",
"event": [
- {
- "listen": "prerequest",
- "script": {
- "exec": [
- ""
- ],
- "type": "text/javascript"
- }
- },
{
"listen": "test",
"script": {
"exec": [
"// Validate status 2xx",
- "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
" pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
- "pm.test(",
- " \"[POST]::/payments/:id/confirm - Content-Type is application/json\",",
- " function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
- " \"application/json\",",
- " );",
- " },",
- ");",
+ "pm.test(\"[GET]::/payments/:id - 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]::/payments/:id/confirm - Response has JSON Body\", function () {",
+ "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
" pm.response.to.have.jsonBody();",
"});",
"",
@@ -3452,104 +3434,89 @@
" );",
"}",
"",
- "// Response body should have value \"processing\" for \"status\"",
+ "// Response body should have value \"cancelled\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'processing'\",",
+ " \"[POST]::/payments/:id - Content check if value for 'status' matches 'requires_capture'\",",
" function () {",
- " pm.expect(jsonData.status).to.eql(\"processing\");",
+ " pm.expect(jsonData.status).to.eql(\"requires_capture\");",
" },",
" );",
- "}"
+ "}",
+ ""
],
"type": "text/javascript"
}
}
],
"request": {
- "auth": {
- "type": "apikey",
- "apikey": [
- {
- "key": "value",
- "value": "{{publishable_key}}",
- "type": "string"
- },
- {
- "key": "key",
- "value": "api-key",
- "type": "string"
- },
- {
- "key": "in",
- "value": "header",
- "type": "string"
- }
- ]
- },
- "method": "POST",
+ "method": "GET",
"header": [
- {
- "key": "Content-Type",
- "value": "application/json"
- },
{
"key": "Accept",
"value": "application/json"
}
],
- "body": {
- "mode": "raw",
- "options": {
- "raw": {
- "language": "json"
- }
- },
- "raw": "{\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4111111111111111\",\"card_exp_month\":\"10\",\"card_exp_year\":\"69\",\"card_holder_name\":\"\",\"card_cvc\":\"123\"}},\"client_secret\":\"{{client_secret}}\",\"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\":\"125.0.0.1\"}}"
- },
"url": {
- "raw": "{{baseUrl}}/payments/:id/confirm",
+ "raw": "{{baseUrl}}/payments/:id?force_sync=true",
"host": [
"{{baseUrl}}"
],
"path": [
"payments",
- ":id",
- "confirm"
+ ":id"
],
- "variable": [
+ "query": [
{
- "key": "id",
- "value": "{{payment_id}}",
- "description": "(Required) unique payment id"
+ "key": "force_sync",
+ "value": "true"
+ }
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
}
]
},
- "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API"
+ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
},
"response": []
},
{
- "name": "Payments - Retrieve",
+ "name": "Payments - Cancel",
"event": [
+ {
+ "listen": "prerequest",
+ "script": {
+ "exec": [
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ },
{
"listen": "test",
"script": {
"exec": [
"// Validate status 2xx",
- "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
+ "pm.test(\"[POST]::/payments/:id/cancel - Status code is 2xx\", function () {",
" pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
- "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
- " \"application/json\",",
- " );",
- "});",
+ "pm.test(",
+ " \"[POST]::/payments/:id/cancel - 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(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
+ "pm.test(\"[POST]::/payments/:id/cancel - Response has JSON Body\", function () {",
" pm.response.to.have.jsonBody();",
"});",
"",
@@ -3572,19 +3539,6 @@
" );",
"}",
"",
- "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
- "if (jsonData?.mandate_id) {",
- " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
- " console.log(",
- " \"- use {{mandate_id}} as collection variable for value\",",
- " jsonData.mandate_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
- " );",
- "}",
- "",
"// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
"if (jsonData?.client_secret) {",
" pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
@@ -3598,42 +3552,51 @@
" );",
"}",
"",
- "// Response body should have value \"succeeded\" for \"status\"",
+ "// Response body should have value \"cancelled\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments:id - Content check if value for 'status' matches 'succeeded'\",",
+ " \"[POST]::/payments/:id/cancel - Content check if value for 'status' matches 'processing'\",",
" function () {",
- " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " pm.expect(jsonData.status).to.eql(\"processing\");",
" },",
" );",
- "}"
+ "}",
+ ""
],
"type": "text/javascript"
}
}
],
"request": {
- "method": "GET",
+ "method": "POST",
"header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
{
"key": "Accept",
"value": "application/json"
}
],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"cancellation_reason\":\"user_cancel\"}"
+ },
"url": {
- "raw": "{{baseUrl}}/payments/:id?force_sync=true",
+ "raw": "{{baseUrl}}/payments/:id/cancel",
"host": [
"{{baseUrl}}"
],
"path": [
"payments",
- ":id"
- ],
- "query": [
- {
- "key": "force_sync",
- "value": "true"
- }
+ ":id",
+ "cancel"
],
"variable": [
{
@@ -3643,46 +3606,31 @@
}
]
},
- "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ "description": "A Payment could can be cancelled when it is in one of these statuses: requires_payment_method, requires_capture, requires_confirmation, requires_customer_action"
},
"response": []
- }
- ]
- },
- {
- "name": "Scenario3-Create payment without PMD",
- "item": [
+ },
{
- "name": "Payments - Create",
+ "name": "Payments - Retrieve-copy",
"event": [
- {
- "listen": "prerequest",
- "script": {
- "exec": [
- "pm.environment.set(\"random_number\", _.random(1000, 100000));",
- ""
- ],
- "type": "text/javascript"
- }
- },
{
"listen": "test",
"script": {
"exec": [
"// Validate status 2xx",
- "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
" pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
- "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ "pm.test(\"[GET]::/payments/:id - 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]::/payments - Response has JSON Body\", function () {",
+ "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
" pm.response.to.have.jsonBody();",
"});",
"",
@@ -3731,12 +3679,12 @@
" );",
"}",
"",
- "// Response body should have value \"requires_payment_method\" for \"status\"",
+ "// Response body should have value \"cancelled\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'\",",
+ " \"[POST]::/payments/:id - Content check if value for 'status' matches 'cancelled'\",",
" function () {",
- " pm.expect(jsonData.status).to.eql(\"requires_payment_method\");",
+ " pm.expect(jsonData.status).to.eql(\"cancelled\");",
" },",
" );",
"}",
@@ -3747,46 +3695,53 @@
}
],
"request": {
- "method": "POST",
+ "method": "GET",
"header": [
- {
- "key": "Content-Type",
- "value": "application/json"
- },
{
"key": "Accept",
"value": "application/json"
}
],
- "body": {
- "mode": "raw",
- "options": {
- "raw": {
- "language": "json"
- }
- },
- "raw": "{\"amount\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"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://duck.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
- },
"url": {
- "raw": "{{baseUrl}}/payments",
+ "raw": "{{baseUrl}}/payments/:id?force_sync=true",
"host": [
"{{baseUrl}}"
],
"path": [
- "payments"
+ "payments",
+ ":id"
+ ],
+ "query": [
+ {
+ "key": "force_sync",
+ "value": "true"
+ }
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
]
},
- "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
},
"response": []
- },
+ }
+ ]
+ },
+ {
+ "name": "Scenario6-Refund full payment",
+ "item": [
{
- "name": "Payments - Confirm",
+ "name": "Payments - Create",
"event": [
{
"listen": "prerequest",
"script": {
"exec": [
+ "pm.environment.set(\"random_number\", _.random(1000, 100000));",
""
],
"type": "text/javascript"
@@ -3796,23 +3751,23 @@
"listen": "test",
"script": {
"exec": [
+ "// Set the environment variable 'amount' with the value from the response",
+ "pm.environment.set(\"amount\", pm.response.json().amount);",
+ "",
"// Validate status 2xx",
- "pm.test(\"[POST]::/payments/:id/confirm - Status code is 2xx\", function () {",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
" pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
- "pm.test(",
- " \"[POST]::/payments/:id/confirm - Content-Type is application/json\",",
- " function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
- " \"application/json\",",
- " );",
- " },",
- ");",
+ "pm.test(\"[POST]::/payments - 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]::/payments/:id/confirm - Response has JSON Body\", function () {",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
" pm.response.to.have.jsonBody();",
"});",
"",
@@ -3864,7 +3819,7 @@
"// Response body should have value \"succeeded\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments:id/confirm - Content check if value for 'status' matches 'processing'\",",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'processing'\",",
" function () {",
" pm.expect(jsonData.status).to.eql(\"processing\");",
" },",
@@ -3877,26 +3832,6 @@
}
],
"request": {
- "auth": {
- "type": "apikey",
- "apikey": [
- {
- "key": "value",
- "value": "{{publishable_key}}",
- "type": "string"
- },
- {
- "key": "key",
- "value": "api-key",
- "type": "string"
- },
- {
- "key": "in",
- "value": "header",
- "type": "string"
- }
- ]
- },
"method": "POST",
"header": [
{
@@ -3915,27 +3850,18 @@
"language": "json"
}
},
- "raw": "{\"client_secret\":\"{{client_secret}}\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4111111111111111\",\"card_exp_month\":\"10\",\"card_exp_year\":\"69\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}}}"
+ "raw": "{\"amount\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"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://duck.com\",\"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\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
},
"url": {
- "raw": "{{baseUrl}}/payments/:id/confirm",
+ "raw": "{{baseUrl}}/payments",
"host": [
"{{baseUrl}}"
],
"path": [
- "payments",
- ":id",
- "confirm"
- ],
- "variable": [
- {
- "key": "id",
- "value": "{{payment_id}}",
- "description": "(Required) unique payment id"
- }
+ "payments"
]
},
- "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API"
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
},
"response": []
},
@@ -4008,10 +3934,10 @@
" );",
"}",
"",
- "// Response body should have value \"succeeded\" for \"status\"",
+ "// Response body should have value \"Succeeded\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments:id - Content check if value for 'status' matches 'succeeded'\",",
+ " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",",
" function () {",
" pm.expect(jsonData.status).to.eql(\"succeeded\");",
" },",
@@ -4057,20 +3983,14 @@
"description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
},
"response": []
- }
- ]
- },
- {
- "name": "Scenario4-Create payment with Manual capture",
- "item": [
+ },
{
- "name": "Payments - Create",
+ "name": "Refunds - Create",
"event": [
{
"listen": "prerequest",
"script": {
"exec": [
- "pm.environment.set(\"random_number\", _.random(1000, 100000));",
""
],
"type": "text/javascript"
@@ -4080,76 +4000,56 @@
"listen": "test",
"script": {
"exec": [
- "pm.environment.set(\"amount\", pm.response.json().amount);",
+ "// Get the value of 'amount' from the environment",
+ "const amount = pm.environment.get(\"amount\");",
"",
"// Validate status 2xx",
- "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ "pm.test(\"[POST]::/refunds - Status code is 2xx\", function () {",
" pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
- "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ "pm.test(\"[POST]::/refunds - 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]::/payments - Response has JSON Body\", function () {",
- " pm.response.to.have.jsonBody();",
- "});",
- "",
"// Set response object as internal variable",
"let jsonData = {};",
"try {",
" jsonData = pm.response.json();",
"} catch (e) {}",
"",
- "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
- "if (jsonData?.payment_id) {",
- " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id",
+ "if (jsonData?.refund_id) {",
+ " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);",
" console.log(",
- " \"- use {{payment_id}} as collection variable for value\",",
- " jsonData.payment_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
- " );",
- "}",
- "",
- "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
- "if (jsonData?.mandate_id) {",
- " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
- " console.log(",
- " \"- use {{mandate_id}} as collection variable for value\",",
- " jsonData.mandate_id,",
+ " \"- use {{refund_id}} as collection variable for value\",",
+ " jsonData.refund_id,",
" );",
"} else {",
" console.log(",
- " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
+ " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",",
" );",
"}",
"",
- "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
- "if (jsonData?.client_secret) {",
- " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
- " console.log(",
- " \"- use {{client_secret}} as collection variable for value\",",
- " jsonData.client_secret,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/refunds - Content check if value for 'status' matches 'pending'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"pending\");",
+ " },",
" );",
"}",
"",
- "// Response body should have value \"requires_capture\" for \"status\"",
+ "// Response body should have value for \"amount\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments - Content check if value for 'status' matches 'processing'\",",
+ " \"[POST]::/refunds - Content check if value for 'amount' matches '{{amount}}'\",",
" function () {",
- " pm.expect(jsonData.status).to.eql(\"processing\");",
+ " pm.expect(jsonData.amount).to.eql(amount);",
" },",
" );",
"}",
@@ -4178,96 +4078,78 @@
"language": "json"
}
},
- "raw": "{\"amount\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"manual\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"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://duck.com\",\"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\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
+ "raw": "{\"payment_id\":\"{{payment_id}}\",\"amount\":\"{{amount}}\",\"reason\":\"Customer returned product\",\"refund_type\":\"instant\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
},
"url": {
- "raw": "{{baseUrl}}/payments",
+ "raw": "{{baseUrl}}/refunds",
"host": [
"{{baseUrl}}"
],
"path": [
- "payments"
+ "refunds"
]
},
- "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ "description": "To create a refund against an already processed payment"
},
"response": []
},
{
- "name": "Payments - Retrieve",
+ "name": "Refunds - Retrieve",
"event": [
{
"listen": "test",
"script": {
"exec": [
+ "// Get the value of 'amount' from the environment",
+ "const refund_amount = pm.environment.get(\"amount\");",
+ "",
"// Validate status 2xx",
- "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
+ "pm.test(\"[GET]::/refunds/:id - Status code is 2xx\", function () {",
" pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
- "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {",
+ "pm.test(\"[GET]::/refunds/:id - 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(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
- " pm.response.to.have.jsonBody();",
- "});",
- "",
"// Set response object as internal variable",
"let jsonData = {};",
"try {",
" jsonData = pm.response.json();",
"} catch (e) {}",
"",
- "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
- "if (jsonData?.payment_id) {",
- " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
- " console.log(",
- " \"- use {{payment_id}} as collection variable for value\",",
- " jsonData.payment_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
- " );",
- "}",
- "",
- "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
- "if (jsonData?.mandate_id) {",
- " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id",
+ "if (jsonData?.refund_id) {",
+ " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);",
" console.log(",
- " \"- use {{mandate_id}} as collection variable for value\",",
- " jsonData.mandate_id,",
+ " \"- use {{refund_id}} as collection variable for value\",",
+ " jsonData.refund_id,",
" );",
"} else {",
" console.log(",
- " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
+ " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",",
" );",
"}",
"",
- "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
- "if (jsonData?.client_secret) {",
- " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
- " console.log(",
- " \"- use {{client_secret}} as collection variable for value\",",
- " jsonData.client_secret,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/refunds - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
" );",
"}",
"",
- "// Response body should have value \"succeeded\" for \"status\"",
+ "// Response body should have value \"{{refund_amount}}\" for \"amount\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments - Content check if value for 'status' matches 'requires_capture'\",",
+ " \"[POST]::/refunds - Content check if value for 'amount' matches '{{refund_amount}}'\",",
" function () {",
- " pm.expect(jsonData.status).to.eql(\"requires_capture\");",
+ " pm.expect(jsonData.amount).to.eql(refund_amount);",
" },",
" );",
"}",
@@ -4286,39 +4168,39 @@
}
],
"url": {
- "raw": "{{baseUrl}}/payments/:id?force_sync=true",
+ "raw": "{{baseUrl}}/refunds/:id",
"host": [
"{{baseUrl}}"
],
"path": [
- "payments",
+ "refunds",
":id"
],
- "query": [
- {
- "key": "force_sync",
- "value": "true"
- }
- ],
"variable": [
{
"key": "id",
- "value": "{{payment_id}}",
- "description": "(Required) unique payment id"
+ "value": "{{refund_id}}",
+ "description": "(Required) unique refund id"
}
]
},
- "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ "description": "To retrieve the properties of a Refund. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
},
"response": []
- },
+ }
+ ]
+ },
+ {
+ "name": "Scenario7-Partial refund",
+ "item": [
{
- "name": "Payments - Capture",
+ "name": "Payments - Create",
"event": [
{
"listen": "prerequest",
"script": {
"exec": [
+ "pm.environment.set(\"random_number\", _.random(1000, 100000));",
""
],
"type": "text/javascript"
@@ -4328,26 +4210,20 @@
"listen": "test",
"script": {
"exec": [
- "// Get the value of 'amount' from the environment",
- "const amount = pm.environment.get(\"amount\");",
- "",
"// Validate status 2xx",
- "pm.test(\"[POST]::/payments/:id/capture - Status code is 2xx\", function () {",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
" pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
- "pm.test(",
- " \"[POST]::/payments/:id/capture - Content-Type is application/json\",",
- " function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
- " \"application/json\",",
- " );",
- " },",
- ");",
+ "pm.test(\"[POST]::/payments - 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]::/payments/:id/capture - Response has JSON Body\", function () {",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
" pm.response.to.have.jsonBody();",
"});",
"",
@@ -4396,35 +4272,15 @@
" );",
"}",
"",
- "// Response body should have value \"succeeded\" for \"status\"",
+ "// Response body should have value \"processing\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]:://payments/:id/capture - Content check if value for 'status' matches 'processing'\",",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'processing'\",",
" function () {",
" pm.expect(jsonData.status).to.eql(\"processing\");",
" },",
" );",
"}",
- "",
- "// Response body should have value \"{{amount}}\" for \"amount\"",
- "if (jsonData?.amount) {",
- " pm.test(",
- " \"[post]:://payments/:id/capture - Content check if value for 'amount' matches '{{amount}}'\",",
- " function () {",
- " pm.expect(jsonData.amount).to.eql(amount);",
- " },",
- " );",
- "}",
- "",
- "// Response body should have value \"{{amount}}\" for \"amount_received\"",
- "if (jsonData?.amount_received) {",
- " pm.test(",
- " \"[POST]::/payments:id/capture - Content check if value for 'amount_received' matches '{{amount}}'\",",
- " function () {",
- " pm.expect(jsonData.amount_received).to.eql(amount);",
- " },",
- " );",
- "}",
""
],
"type": "text/javascript"
@@ -4450,32 +4306,23 @@
"language": "json"
}
},
- "raw": "{\"amount_to_capture\":\"{{amount}}\",\"statement_descriptor_name\":\"Joseph\",\"statement_descriptor_suffix\":\"JS\"}"
+ "raw": "{\"amount\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"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://duck.com\",\"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\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
},
"url": {
- "raw": "{{baseUrl}}/payments/:id/capture",
+ "raw": "{{baseUrl}}/payments",
"host": [
"{{baseUrl}}"
],
"path": [
- "payments",
- ":id",
- "capture"
- ],
- "variable": [
- {
- "key": "id",
- "value": "{{payment_id}}",
- "description": "(Required) unique payment id"
- }
+ "payments"
]
},
- "description": "To capture the funds for an uncaptured payment"
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
},
"response": []
},
{
- "name": "Payments - Retrieve-copy",
+ "name": "Payments - Retrieve",
"event": [
{
"listen": "test",
@@ -4543,10 +4390,10 @@
" );",
"}",
"",
- "// Response body should have value \"succeeded\" for \"status\"",
+ "// Response body should have value \"Succeeded\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",",
+ " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",",
" function () {",
" pm.expect(jsonData.status).to.eql(\"succeeded\");",
" },",
@@ -4592,20 +4439,14 @@
"description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
},
"response": []
- }
- ]
- },
- {
- "name": "Scenario5-Void the payment",
- "item": [
+ },
{
- "name": "Payments - Create",
+ "name": "Refunds - Create",
"event": [
{
"listen": "prerequest",
"script": {
"exec": [
- "pm.environment.set(\"random_number\", _.random(1000, 100000));",
""
],
"type": "text/javascript"
@@ -4616,73 +4457,52 @@
"script": {
"exec": [
"// Validate status 2xx",
- "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ "pm.test(\"[POST]::/refunds - Status code is 2xx\", function () {",
" pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
- "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ "pm.test(\"[POST]::/refunds - 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]::/payments - Response has JSON Body\", function () {",
- " pm.response.to.have.jsonBody();",
- "});",
- "",
"// Set response object as internal variable",
"let jsonData = {};",
"try {",
" jsonData = pm.response.json();",
"} catch (e) {}",
"",
- "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
- "if (jsonData?.payment_id) {",
- " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id",
+ "if (jsonData?.refund_id) {",
+ " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);",
" console.log(",
- " \"- use {{payment_id}} as collection variable for value\",",
- " jsonData.payment_id,",
+ " \"- use {{refund_id}} as collection variable for value\",",
+ " jsonData.refund_id,",
" );",
"} else {",
" console.log(",
- " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",",
" );",
"}",
"",
- "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
- "if (jsonData?.mandate_id) {",
- " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
- " console.log(",
- " \"- use {{mandate_id}} as collection variable for value\",",
- " jsonData.mandate_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/refunds - Content check if value for 'status' matches 'pending'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"pending\");",
+ " },",
" );",
"}",
"",
- "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
- "if (jsonData?.client_secret) {",
- " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
- " console.log(",
- " \"- use {{client_secret}} as collection variable for value\",",
- " jsonData.client_secret,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
- " );",
- "}",
- "",
- "// Response body should have value \"requires_capture\" for \"status\"",
+ "// Response body should have value \"540\" for \"amount\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments - Content check if value for 'status' matches 'processing'\",",
+ " \"[POST]::/refunds - Content check if value for 'amount' matches '100'\",",
" function () {",
- " pm.expect(jsonData.status).to.eql(\"processing\");",
+ " pm.expect(jsonData.amount).to.eql(100);",
" },",
" );",
"}",
@@ -4711,96 +4531,75 @@
"language": "json"
}
},
- "raw": "{\"amount\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"manual\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"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://duck.com\",\"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\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
+ "raw": "{\"payment_id\":\"{{payment_id}}\",\"amount\":100,\"reason\":\"Customer returned product\",\"refund_type\":\"instant\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
},
"url": {
- "raw": "{{baseUrl}}/payments",
+ "raw": "{{baseUrl}}/refunds",
"host": [
"{{baseUrl}}"
],
"path": [
- "payments"
+ "refunds"
]
},
- "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ "description": "To create a refund against an already processed payment"
},
"response": []
},
{
- "name": "Payments - Retrieve",
+ "name": "Refunds - Retrieve",
"event": [
{
"listen": "test",
"script": {
"exec": [
"// Validate status 2xx",
- "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
+ "pm.test(\"[GET]::/refunds/:id - Status code is 2xx\", function () {",
" pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
- "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {",
+ "pm.test(\"[GET]::/refunds/:id - 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(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
- " pm.response.to.have.jsonBody();",
- "});",
- "",
"// Set response object as internal variable",
"let jsonData = {};",
"try {",
" jsonData = pm.response.json();",
"} catch (e) {}",
"",
- "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
- "if (jsonData?.payment_id) {",
- " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
- " console.log(",
- " \"- use {{payment_id}} as collection variable for value\",",
- " jsonData.payment_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
- " );",
- "}",
- "",
- "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
- "if (jsonData?.mandate_id) {",
- " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id",
+ "if (jsonData?.refund_id) {",
+ " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);",
" console.log(",
- " \"- use {{mandate_id}} as collection variable for value\",",
- " jsonData.mandate_id,",
+ " \"- use {{refund_id}} as collection variable for value\",",
+ " jsonData.refund_id,",
" );",
"} else {",
" console.log(",
- " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
+ " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",",
" );",
"}",
"",
- "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
- "if (jsonData?.client_secret) {",
- " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
- " console.log(",
- " \"- use {{client_secret}} as collection variable for value\",",
- " jsonData.client_secret,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/refunds - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
" );",
"}",
"",
- "// Response body should have value \"cancelled\" for \"status\"",
+ "// Response body should have value \"6540\" for \"amount\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments/:id - Content check if value for 'status' matches 'requires_capture'\",",
+ " \"[POST]::/refunds - Content check if value for 'amount' matches '100'\",",
" function () {",
- " pm.expect(jsonData.status).to.eql(\"requires_capture\");",
+ " pm.expect(jsonData.amount).to.eql(100);",
" },",
" );",
"}",
@@ -4819,34 +4618,28 @@
}
],
"url": {
- "raw": "{{baseUrl}}/payments/:id?force_sync=true",
+ "raw": "{{baseUrl}}/refunds/:id",
"host": [
"{{baseUrl}}"
],
"path": [
- "payments",
+ "refunds",
":id"
],
- "query": [
- {
- "key": "force_sync",
- "value": "true"
- }
- ],
"variable": [
{
"key": "id",
- "value": "{{payment_id}}",
- "description": "(Required) unique payment id"
+ "value": "{{refund_id}}",
+ "description": "(Required) unique refund id"
}
]
},
- "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ "description": "To retrieve the properties of a Refund. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
},
"response": []
},
{
- "name": "Payments - Cancel",
+ "name": "Refunds - Create-copy",
"event": [
{
"listen": "prerequest",
@@ -4862,23 +4655,15 @@
"script": {
"exec": [
"// Validate status 2xx",
- "pm.test(\"[POST]::/payments/:id/cancel - Status code is 2xx\", function () {",
+ "pm.test(\"[POST]::/refunds - Status code is 2xx\", function () {",
" pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
- "pm.test(",
- " \"[POST]::/payments/:id/cancel - 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]::/payments/:id/cancel - Response has JSON Body\", function () {",
- " pm.response.to.have.jsonBody();",
+ "pm.test(\"[POST]::/refunds - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
"});",
"",
"// Set response object as internal variable",
@@ -4887,38 +4672,35 @@
" jsonData = pm.response.json();",
"} catch (e) {}",
"",
- "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
- "if (jsonData?.payment_id) {",
- " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id",
+ "if (jsonData?.refund_id) {",
+ " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);",
" console.log(",
- " \"- use {{payment_id}} as collection variable for value\",",
- " jsonData.payment_id,",
+ " \"- use {{refund_id}} as collection variable for value\",",
+ " jsonData.refund_id,",
" );",
"} else {",
" console.log(",
- " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",",
" );",
"}",
"",
- "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
- "if (jsonData?.client_secret) {",
- " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
- " console.log(",
- " \"- use {{client_secret}} as collection variable for value\",",
- " jsonData.client_secret,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/refunds - Content check if value for 'status' matches 'pending'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"pending\");",
+ " },",
" );",
"}",
"",
- "// Response body should have value \"cancelled\" for \"status\"",
+ "// Response body should have value \"1000\" for \"amount\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments/:id/cancel - Content check if value for 'status' matches 'processing'\",",
+ " \"[POST]::/refunds - Content check if value for 'amount' matches '10'\",",
" function () {",
- " pm.expect(jsonData.status).to.eql(\"processing\");",
+ " pm.expect(jsonData.amount).to.eql(10);",
" },",
" );",
"}",
@@ -4947,27 +4729,110 @@
"language": "json"
}
},
- "raw": "{\"cancellation_reason\":\"user_cancel\"}"
+ "raw": "{\"payment_id\":\"{{payment_id}}\",\"amount\":10,\"reason\":\"Customer returned product\",\"refund_type\":\"instant\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
},
"url": {
- "raw": "{{baseUrl}}/payments/:id/cancel",
+ "raw": "{{baseUrl}}/refunds",
"host": [
"{{baseUrl}}"
],
"path": [
- "payments",
- ":id",
- "cancel"
+ "refunds"
+ ]
+ },
+ "description": "To create a refund against an already processed payment"
+ },
+ "response": []
+ },
+ {
+ "name": "Refunds - Retrieve-copy",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[GET]::/refunds/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/refunds/:id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id",
+ "if (jsonData?.refund_id) {",
+ " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);",
+ " console.log(",
+ " \"- use {{refund_id}} as collection variable for value\",",
+ " jsonData.refund_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/refunds - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"6540\" for \"amount\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/refunds - Content check if value for 'amount' matches '10'\",",
+ " function () {",
+ " pm.expect(jsonData.amount).to.eql(10);",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/refunds/:id",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "refunds",
+ ":id"
],
"variable": [
{
"key": "id",
- "value": "{{payment_id}}",
- "description": "(Required) unique payment id"
+ "value": "{{refund_id}}",
+ "description": "(Required) unique refund id"
}
]
},
- "description": "A Payment could can be cancelled when it is in one of these statuses: requires_payment_method, requires_capture, requires_confirmation, requires_customer_action"
+ "description": "To retrieve the properties of a Refund. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
},
"response": []
},
@@ -5040,15 +4905,20 @@
" );",
"}",
"",
- "// Response body should have value \"cancelled\" for \"status\"",
+ "// Response body should have value \"Succeeded\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments/:id - Content check if value for 'status' matches 'cancelled'\",",
+ " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",",
" function () {",
- " pm.expect(jsonData.status).to.eql(\"cancelled\");",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
" },",
" );",
"}",
+ "",
+ "// Response body should have \"refunds\"",
+ "pm.test(\"[POST]::/payments - Content check if 'refunds' exists\", function () {",
+ " pm.expect(typeof jsonData.refunds !== \"undefined\").to.be.true;",
+ "});",
""
],
"type": "text/javascript"
@@ -5093,7 +4963,7 @@
]
},
{
- "name": "Scenario6-Refund full payment",
+ "name": "Scenario8-Create a failure card payment with confirm true",
"item": [
{
"name": "Payments - Create",
@@ -5112,9 +4982,6 @@
"listen": "test",
"script": {
"exec": [
- "// Set the environment variable 'amount' with the value from the response",
- "pm.environment.set(\"amount\", pm.response.json().amount);",
- "",
"// Validate status 2xx",
"pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
" pm.response.to.be.success;",
@@ -5180,9 +5047,38 @@
"// Response body should have value \"succeeded\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments - Content check if value for 'status' matches 'processing'\",",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'failed'\",",
" function () {",
- " pm.expect(jsonData.status).to.eql(\"processing\");",
+ " pm.expect(jsonData.status).to.eql(\"failed\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have \"connector_transaction_id\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'connector_transaction_id' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.connector_transaction_id !== \"undefined\").to.be",
+ " .true;",
+ " },",
+ ");",
+ "",
+ "// Response body should have value \"200\" for \"error_code\"",
+ "if (jsonData?.error_code) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id/confirm - Content check if value for 'error_code' matches '200'\",",
+ " function () {",
+ " pm.expect(jsonData.error_code).to.eql(\"200\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"message - DECLINE\"",
+ "if (jsonData?.error_message) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id/confirm - Content check if value for 'error_message' matches 'DECLINE'\",",
+ " function () {",
+ " pm.expect(jsonData.error_message).to.eql(\"DECLINE\");",
" },",
" );",
"}",
@@ -5211,7 +5107,7 @@
"language": "json"
}
},
- "raw": "{\"amount\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"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://duck.com\",\"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\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
+ "raw": "{\"amount\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":true,\"business_country\":\"US\",\"business_label\":\"default\",\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"customer_id\":\"bernard123\",\"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://duck.com\",\"setup_future_usage\":\"on_session\",\"customer_acceptance\":{\"acceptance_type\":\"online\",\"accepted_at\":\"2022-09-10T10:11:12Z\",\"online\":{\"ip_address\":\"123.32.25.123\",\"user_agent\":\"Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36\"}},\"payment_method\":\"card\",\"payment_method_type\":\"debit\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"01\",\"card_exp_year\":\"26\",\"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\":\"John\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\",\"last_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
},
"url": {
"raw": "{{baseUrl}}/payments",
@@ -5229,6 +5125,15 @@
{
"name": "Payments - Retrieve",
"event": [
+ {
+ "listen": "prerequest",
+ "script": {
+ "exec": [
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ },
{
"listen": "test",
"script": {
@@ -5298,9 +5203,38 @@
"// Response body should have value \"Succeeded\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",",
+ " \"[POST]::/payments/:id - Content check if value for 'status' matches 'failed'\",",
" function () {",
- " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " pm.expect(jsonData.status).to.eql(\"failed\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have \"connector_transaction_id\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'connector_transaction_id' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.connector_transaction_id !== \"undefined\").to.be",
+ " .true;",
+ " },",
+ ");",
+ "",
+ "// Response body should have value \"200\" for \"error_code\"",
+ "if (jsonData?.error_code) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id/confirm - Content check if value for 'error_code' matches '200'\",",
+ " function () {",
+ " pm.expect(jsonData.error_code).to.eql(\"200\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"message - DECLINE\"",
+ "if (jsonData?.error_message) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id/confirm - Content check if value for 'error_message' matches 'DECLINE'\",",
+ " function () {",
+ " pm.expect(jsonData.error_message).to.eql(\"DECLINE\");",
" },",
" );",
"}",
@@ -5344,14 +5278,20 @@
"description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
},
"response": []
- },
+ }
+ ]
+ },
+ {
+ "name": "Scenario9-Update amount with automatic capture",
+ "item": [
{
- "name": "Refunds - Create",
+ "name": "Payments - Create",
"event": [
{
"listen": "prerequest",
"script": {
"exec": [
+ "pm.environment.set(\"random_number\", _.random(1000, 100000));",
""
],
"type": "text/javascript"
@@ -5361,59 +5301,65 @@
"listen": "test",
"script": {
"exec": [
- "// Get the value of 'amount' from the environment",
- "const amount = pm.environment.get(\"amount\");",
+ "// Set the environment variable 'amount' with the value from the response",
+ "pm.environment.set(\"amount\", pm.response.json().amount);",
"",
- "// Validate status 2xx",
- "pm.test(\"[POST]::/refunds - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
+ "// Validate status 2xx ",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
- "pm.test(\"[POST]::/refunds - Content-Type is application/json\", function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
- " \"application/json\",",
- " );",
+ "pm.test(\"[POST]::/payments - 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]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
"});",
"",
"// Set response object as internal variable",
"let jsonData = {};",
- "try {",
- " jsonData = pm.response.json();",
- "} catch (e) {}",
+ "try {jsonData = pm.response.json();}catch(e){}",
"",
- "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id",
- "if (jsonData?.refund_id) {",
- " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);",
- " console.log(",
- " \"- use {{refund_id}} as collection variable for value\",",
- " jsonData.refund_id,",
- " );",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);",
"} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",",
- " );",
- "}",
+ " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');",
+ "};",
"",
- "// Response body should have value \"succeeded\" for \"status\"",
- "if (jsonData?.status) {",
- " pm.test(",
- " \"[POST]::/refunds - Content check if value for 'status' matches 'pending'\",",
- " function () {",
- " pm.expect(jsonData.status).to.eql(\"pending\");",
- " },",
- " );",
- "}",
"",
- "// Response body should have value for \"amount\"",
+ "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
+ "if (jsonData?.mandate_id) {",
+ " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');",
+ "};",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');",
+ "};",
+ "",
+ "// pm.collectionVariables - Set customer_id as variable for jsonData.customer_id",
+ "if (jsonData?.customer_id) {",
+ " pm.collectionVariables.set(\"customer_id\", jsonData.customer_id);",
+ " console.log(\"- use {{customer_id}} as collection variable for value\",jsonData.customer_id);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{customer_id}}, as jsonData.customer_id is undefined.');",
+ "};",
+ "// Response body should have value \"requires_payment_method\" for \"status\"",
"if (jsonData?.status) {",
- " pm.test(",
- " \"[POST]::/refunds - Content check if value for 'amount' matches '{{amount}}'\",",
- " function () {",
- " pm.expect(jsonData.amount).to.eql(amount);",
- " },",
- " );",
- "}",
+ "pm.test(\"[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'\", function() {",
+ " pm.expect(jsonData.status).to.eql(\"requires_payment_method\");",
+ "})};",
""
],
"type": "text/javascript"
@@ -5439,81 +5385,70 @@
"language": "json"
}
},
- "raw": "{\"payment_id\":\"{{payment_id}}\",\"amount\":\"{{amount}}\",\"reason\":\"Customer returned product\",\"refund_type\":\"instant\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
+ "raw": "{\"amount\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"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://duck.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
},
"url": {
- "raw": "{{baseUrl}}/refunds",
+ "raw": "{{baseUrl}}/payments",
"host": [
"{{baseUrl}}"
],
"path": [
- "refunds"
+ "payments"
]
},
- "description": "To create a refund against an already processed payment"
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
},
"response": []
},
{
- "name": "Refunds - Retrieve",
+ "name": "Payments - Update",
"event": [
+ {
+ "listen": "prerequest",
+ "script": {
+ "exec": [
+ "// Get the value of 'amount' from the environment",
+ "pm.environment.set(\"another_random_number\", _.random(100, 100000));",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ },
{
"listen": "test",
"script": {
"exec": [
+ "// Set the environment variable 'amount' with the value from the response",
+ "pm.environment.set(\"amount\", pm.response.json().amount);",
+ "",
"// Get the value of 'amount' from the environment",
- "const refund_amount = pm.environment.get(\"amount\");",
+ "const updated_amount = pm.environment.get(\"amount\");",
"",
- "// Validate status 2xx",
- "pm.test(\"[GET]::/refunds/:id - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
+ "// Validate status 2xx ",
+ "pm.test(\"[POST]::/payments/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
- "pm.test(\"[GET]::/refunds/:id - Content-Type is application/json\", function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
- " \"application/json\",",
- " );",
+ "pm.test(\"[POST]::/payments/:id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");",
"});",
"",
- "// Set response object as internal variable",
- "let jsonData = {};",
- "try {",
- " jsonData = pm.response.json();",
- "} catch (e) {}",
+ "// Validate if response has JSON Body ",
+ "pm.test(\"[POST]::/payments/:id - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
"",
- "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id",
- "if (jsonData?.refund_id) {",
- " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);",
- " console.log(",
- " \"- use {{refund_id}} as collection variable for value\",",
- " jsonData.refund_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",",
- " );",
- "}",
"",
- "// Response body should have value \"succeeded\" for \"status\"",
- "if (jsonData?.status) {",
- " pm.test(",
- " \"[POST]::/refunds - Content check if value for 'status' matches 'succeeded'\",",
- " function () {",
- " pm.expect(jsonData.status).to.eql(\"succeeded\");",
- " },",
- " );",
- "}",
+ "// Parse the JSON response",
+ "var jsonData = pm.response.json();",
+ "",
+ "// Check if the 'amount' is equal to \"updated_amount\"",
+ "pm.test(\"[POST]::/payments/:id -Content Check if 'amount' matches '{{updated_amount}}'\", function () {",
+ " pm.expect(jsonData.amount).to.eql(updated_amount);",
+ "});",
+ "",
"",
- "// Response body should have value \"{{refund_amount}}\" for \"amount\"",
- "if (jsonData?.status) {",
- " pm.test(",
- " \"[POST]::/refunds - Content check if value for 'amount' matches '{{refund_amount}}'\",",
- " function () {",
- " pm.expect(jsonData.amount).to.eql(refund_amount);",
- " },",
- " );",
- "}",
""
],
"type": "text/javascript"
@@ -5521,47 +5456,53 @@
}
],
"request": {
- "method": "GET",
+ "method": "POST",
"header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
{
"key": "Accept",
"value": "application/json"
}
],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":\"{{another_random_number}}\",\"amount_to_capture\":\"{{another_random_number}}\"}"
+ },
"url": {
- "raw": "{{baseUrl}}/refunds/:id",
+ "raw": "{{baseUrl}}/payments/:id",
"host": [
"{{baseUrl}}"
],
"path": [
- "refunds",
+ "payments",
":id"
],
"variable": [
{
"key": "id",
- "value": "{{refund_id}}",
- "description": "(Required) unique refund id"
+ "value": "{{payment_id}}"
}
]
},
- "description": "To retrieve the properties of a Refund. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ "description": "To update the properties of a PaymentIntent object. This may include attaching a payment method, or attaching customer object or metadata fields after the Payment is created "
},
"response": []
- }
- ]
- },
- {
- "name": "Scenario7-Partial refund",
- "item": [
+ },
{
- "name": "Payments - Create",
+ "name": "Payments - Confirm",
"event": [
{
"listen": "prerequest",
"script": {
"exec": [
- "pm.environment.set(\"random_number\", _.random(1000, 100000));",
""
],
"type": "text/javascript"
@@ -5571,77 +5512,45 @@
"listen": "test",
"script": {
"exec": [
- "// Validate status 2xx",
- "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
- "});",
+ "// Get the value of 'amount' from the environment",
+ "const amount = pm.environment.get(\"amount\");",
"",
- "// Validate if response header has matching content-type",
- "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
- " \"application/json\",",
- " );",
+ "// Validate status 2xx ",
+ "pm.test(\"[POST]::/payments/:id/confirm - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
"});",
"",
- "// Validate if response has JSON Body",
- "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
- " pm.response.to.have.jsonBody();",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments/:id/confirm - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");",
"});",
"",
"// Set response object as internal variable",
"let jsonData = {};",
- "try {",
- " jsonData = pm.response.json();",
- "} catch (e) {}",
+ "try {jsonData = pm.response.json();}catch(e){}",
"",
- "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
- "if (jsonData?.payment_id) {",
- " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
- " console.log(",
- " \"- use {{payment_id}} as collection variable for value\",",
- " jsonData.payment_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
- " );",
- "}",
+ "// Validate if response has JSON Body ",
+ "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
"",
- "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
- "if (jsonData?.mandate_id) {",
- " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
- " console.log(",
- " \"- use {{mandate_id}} as collection variable for value\",",
- " jsonData.mandate_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
- " );",
- "}",
+ "//// Response body should have value \"processing\" for \"status\"",
+ "if (jsonData?.status) {",
+ "pm.test(\"[POST]::/payments - Content check if value for 'status' matches 'processing'\", function() {",
+ " pm.expect(jsonData.status).to.eql(\"processing\");",
+ "})};",
"",
- "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
- "if (jsonData?.client_secret) {",
- " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
- " console.log(",
- " \"- use {{client_secret}} as collection variable for value\",",
- " jsonData.client_secret,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
- " );",
- "}",
"",
- "// Response body should have value \"processing\" for \"status\"",
- "if (jsonData?.status) {",
- " pm.test(",
- " \"[POST]::/payments - Content check if value for 'status' matches 'processing'\",",
- " function () {",
- " pm.expect(jsonData.status).to.eql(\"processing\");",
- " },",
- " );",
- "}",
+ "// Check if the 'amount' is equal to \"amount\"",
+ "pm.test(\"[POST]::/payments/:id -Content Check if 'amount' matches '{{amount}}' \", function () {",
+ " pm.expect(jsonData.amount).to.eql(amount);",
+ "});",
+ "",
+ "//// Response body should have value \"amount_received\" for \"amount\"",
+ "if (jsonData?.amount_received) {",
+ "pm.test(\"[POST]::/payments - Content check if value for 'amount_received' matches '{{amount}}'\", function() {",
+ " pm.expect(jsonData.amount_received).to.eql(amount);",
+ "})};",
""
],
"type": "text/javascript"
@@ -5649,6 +5558,26 @@
}
],
"request": {
+ "auth": {
+ "type": "apikey",
+ "apikey": [
+ {
+ "key": "value",
+ "value": "{{publishable_key}}",
+ "type": "string"
+ },
+ {
+ "key": "key",
+ "value": "api-key",
+ "type": "string"
+ },
+ {
+ "key": "in",
+ "value": "header",
+ "type": "string"
+ }
+ ]
+ },
"method": "POST",
"header": [
{
@@ -5658,6 +5587,12 @@
{
"key": "Accept",
"value": "application/json"
+ },
+ {
+ "key": "publishable_key",
+ "value": "",
+ "type": "text",
+ "disabled": true
}
],
"body": {
@@ -5667,99 +5602,109 @@
"language": "json"
}
},
- "raw": "{\"amount\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"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://duck.com\",\"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\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
+ "raw": "{\"client_secret\":\"{{client_secret}}\",\"payment_method\":\"card\",\"payment_method_type\":\"debit\",\"payment_method_data\":{\"card\":{\"card_number\":\"4111111111111111\",\"card_exp_month\":\"03\",\"card_exp_year\":\"69\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"737\"}},\"setup_future_usage\":\"on_session\",\"customer_acceptance\":{\"acceptance_type\":\"online\",\"accepted_at\":\"2022-09-10T10:11:12Z\",\"online\":{\"ip_address\":\"123.32.25.123\",\"user_agent\":\"Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36\"}},\"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\":\"128.0.0.1\"}}"
},
"url": {
- "raw": "{{baseUrl}}/payments",
+ "raw": "{{baseUrl}}/payments/:id/confirm",
"host": [
"{{baseUrl}}"
],
"path": [
- "payments"
+ "payments",
+ ":id",
+ "confirm"
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}"
+ }
]
},
- "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API"
},
"response": []
},
{
"name": "Payments - Retrieve",
"event": [
+ {
+ "listen": "prerequest",
+ "script": {
+ "exec": [
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ },
{
"listen": "test",
"script": {
"exec": [
- "// Validate status 2xx",
+ "// Get the value of 'amount' from the environment",
+ "const amount = pm.environment.get(\"amount\");",
+ "",
+ "// Validate status 2xx ",
"pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
+ " pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
"pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
- " \"application/json\",",
- " );",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");",
"});",
"",
- "// Validate if response has JSON Body",
+ "// Validate if response has JSON Body ",
"pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
- " pm.response.to.have.jsonBody();",
+ " pm.response.to.have.jsonBody();",
"});",
"",
"// Set response object as internal variable",
"let jsonData = {};",
- "try {",
- " jsonData = pm.response.json();",
- "} catch (e) {}",
+ "try {jsonData = pm.response.json();}catch(e){}",
"",
"// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
"if (jsonData?.payment_id) {",
- " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
- " console.log(",
- " \"- use {{payment_id}} as collection variable for value\",",
- " jsonData.payment_id,",
- " );",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);",
"} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
- " );",
- "}",
+ " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');",
+ "};",
+ "",
"",
"// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
"if (jsonData?.mandate_id) {",
- " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
- " console.log(",
- " \"- use {{mandate_id}} as collection variable for value\",",
- " jsonData.mandate_id,",
- " );",
+ " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);",
"} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
- " );",
- "}",
+ " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');",
+ "};",
"",
"// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
"if (jsonData?.client_secret) {",
- " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
- " console.log(",
- " \"- use {{client_secret}} as collection variable for value\",",
- " jsonData.client_secret,",
- " );",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);",
"} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
- " );",
- "}",
+ " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');",
+ "};",
"",
- "// Response body should have value \"Succeeded\" for \"status\"",
+ "//// Response body should have value \"succeeded\" for \"status\"",
"if (jsonData?.status) {",
- " pm.test(",
- " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",",
- " function () {",
- " pm.expect(jsonData.status).to.eql(\"succeeded\");",
- " },",
- " );",
- "}",
+ "pm.test(\"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\", function() {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ "})};",
+ "",
+ "",
+ "// Check if the 'amount' is equal to \"amount\"",
+ "pm.test(\"[POST]::/payments/:id -Content Check if 'amount' matches '{{amount}}' \", function () {",
+ " pm.expect(jsonData.amount).to.eql(amount);",
+ "});",
+ "",
+ "//// Response body should have value \"amount_received\" for \"amount\"",
+ "if (jsonData?.amount_received) {",
+ "pm.test(\"[POST]::/payments - Content check if value for 'amount_received' matches '{{amount}}'\", function() {",
+ " pm.expect(jsonData.amount_received).to.eql(amount);",
+ "})};",
""
],
"type": "text/javascript"
@@ -5800,14 +5745,20 @@
"description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
},
"response": []
- },
+ }
+ ]
+ },
+ {
+ "name": "Scenario9a-Update amount with manual capture",
+ "item": [
{
- "name": "Refunds - Create",
+ "name": "Payments - Create",
"event": [
{
"listen": "prerequest",
"script": {
"exec": [
+ "pm.environment.set(\"random_number\", _.random(100, 100000));",
""
],
"type": "text/javascript"
@@ -5817,56 +5768,65 @@
"listen": "test",
"script": {
"exec": [
- "// Validate status 2xx",
- "pm.test(\"[POST]::/refunds - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
+ "// Set the environment variable 'amount' with the value from the response",
+ "pm.environment.set(\"amount\", pm.response.json().amount);",
+ "",
+ "// Validate status 2xx ",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
- "pm.test(\"[POST]::/refunds - Content-Type is application/json\", function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
- " \"application/json\",",
- " );",
+ "pm.test(\"[POST]::/payments - 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]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
"});",
"",
"// Set response object as internal variable",
"let jsonData = {};",
- "try {",
- " jsonData = pm.response.json();",
- "} catch (e) {}",
+ "try {jsonData = pm.response.json();}catch(e){}",
"",
- "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id",
- "if (jsonData?.refund_id) {",
- " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);",
- " console.log(",
- " \"- use {{refund_id}} as collection variable for value\",",
- " jsonData.refund_id,",
- " );",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);",
"} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",",
- " );",
- "}",
+ " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');",
+ "};",
"",
- "// Response body should have value \"succeeded\" for \"status\"",
- "if (jsonData?.status) {",
- " pm.test(",
- " \"[POST]::/refunds - Content check if value for 'status' matches 'pending'\",",
- " function () {",
- " pm.expect(jsonData.status).to.eql(\"pending\");",
- " },",
- " );",
- "}",
"",
- "// Response body should have value \"540\" for \"amount\"",
+ "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
+ "if (jsonData?.mandate_id) {",
+ " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');",
+ "};",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');",
+ "};",
+ "",
+ "// pm.collectionVariables - Set customer_id as variable for jsonData.customer_id",
+ "if (jsonData?.customer_id) {",
+ " pm.collectionVariables.set(\"customer_id\", jsonData.customer_id);",
+ " console.log(\"- use {{customer_id}} as collection variable for value\",jsonData.customer_id);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{customer_id}}, as jsonData.customer_id is undefined.');",
+ "};",
+ "// Response body should have value \"requires_payment_method\" for \"status\"",
"if (jsonData?.status) {",
- " pm.test(",
- " \"[POST]::/refunds - Content check if value for 'amount' matches '100'\",",
- " function () {",
- " pm.expect(jsonData.amount).to.eql(100);",
- " },",
- " );",
- "}",
+ "pm.test(\"[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'\", function() {",
+ " pm.expect(jsonData.status).to.eql(\"requires_payment_method\");",
+ "})};",
""
],
"type": "text/javascript"
@@ -5892,78 +5852,70 @@
"language": "json"
}
},
- "raw": "{\"payment_id\":\"{{payment_id}}\",\"amount\":100,\"reason\":\"Customer returned product\",\"refund_type\":\"instant\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
+ "raw": "{\"amount\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"manual\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"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://duck.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
},
"url": {
- "raw": "{{baseUrl}}/refunds",
+ "raw": "{{baseUrl}}/payments",
"host": [
"{{baseUrl}}"
],
"path": [
- "refunds"
+ "payments"
]
},
- "description": "To create a refund against an already processed payment"
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
},
"response": []
},
{
- "name": "Refunds - Retrieve",
+ "name": "Payments - Update",
"event": [
+ {
+ "listen": "prerequest",
+ "script": {
+ "exec": [
+ "// Get the value of 'amount' from the environment",
+ "pm.environment.set(\"another_random_number\", _.random(100, 100000));",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ },
{
"listen": "test",
"script": {
"exec": [
- "// Validate status 2xx",
- "pm.test(\"[GET]::/refunds/:id - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
+ "// Set the environment variable 'amount' with the value from the response",
+ "pm.environment.set(\"amount\", pm.response.json().amount);",
+ "",
+ "// Get the value of 'amount' from the environment",
+ "const updated_amount = pm.environment.get(\"amount\");",
+ "",
+ "// Validate status 2xx ",
+ "pm.test(\"[POST]::/payments/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
- "pm.test(\"[GET]::/refunds/:id - Content-Type is application/json\", function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
- " \"application/json\",",
- " );",
+ "pm.test(\"[POST]::/payments/:id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");",
"});",
"",
- "// Set response object as internal variable",
- "let jsonData = {};",
- "try {",
- " jsonData = pm.response.json();",
- "} catch (e) {}",
+ "// Validate if response has JSON Body ",
+ "pm.test(\"[POST]::/payments/:id - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
"",
- "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id",
- "if (jsonData?.refund_id) {",
- " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);",
- " console.log(",
- " \"- use {{refund_id}} as collection variable for value\",",
- " jsonData.refund_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",",
- " );",
- "}",
"",
- "// Response body should have value \"succeeded\" for \"status\"",
- "if (jsonData?.status) {",
- " pm.test(",
- " \"[POST]::/refunds - Content check if value for 'status' matches 'succeeded'\",",
- " function () {",
- " pm.expect(jsonData.status).to.eql(\"succeeded\");",
- " },",
- " );",
- "}",
+ "// Parse the JSON response",
+ "var jsonData = pm.response.json();",
+ "",
+ "// Check if the 'amount' is equal to \"updated_amount\"",
+ "pm.test(\"[POST]::/payments/:id -Content Check if 'amount' matches '{{updated_amount}}'\", function () {",
+ " pm.expect(jsonData.amount).to.eql(updated_amount);",
+ "});",
+ "",
"",
- "// Response body should have value \"6540\" for \"amount\"",
- "if (jsonData?.status) {",
- " pm.test(",
- " \"[POST]::/refunds - Content check if value for 'amount' matches '100'\",",
- " function () {",
- " pm.expect(jsonData.amount).to.eql(100);",
- " },",
- " );",
- "}",
""
],
"type": "text/javascript"
@@ -5971,36 +5923,48 @@
}
],
"request": {
- "method": "GET",
+ "method": "POST",
"header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
{
"key": "Accept",
"value": "application/json"
}
],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":\"{{another_random_number}}\",\"amount_to_capture\":\"{{another_random_number}}\"}"
+ },
"url": {
- "raw": "{{baseUrl}}/refunds/:id",
+ "raw": "{{baseUrl}}/payments/:id",
"host": [
"{{baseUrl}}"
],
"path": [
- "refunds",
+ "payments",
":id"
],
"variable": [
{
"key": "id",
- "value": "{{refund_id}}",
- "description": "(Required) unique refund id"
+ "value": "{{payment_id}}"
}
]
},
- "description": "To retrieve the properties of a Refund. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ "description": "To update the properties of a PaymentIntent object. This may include attaching a payment method, or attaching customer object or metadata fields after the Payment is created "
},
"response": []
},
{
- "name": "Refunds - Create-copy",
+ "name": "Payments - Confirm",
"event": [
{
"listen": "prerequest",
@@ -6015,56 +5979,45 @@
"listen": "test",
"script": {
"exec": [
- "// Validate status 2xx",
- "pm.test(\"[POST]::/refunds - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
+ "// Get the value of 'amount' from the environment",
+ "const amount = pm.environment.get(\"amount\");",
+ "",
+ "// Validate status 2xx ",
+ "pm.test(\"[POST]::/payments/:id/confirm - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
- "pm.test(\"[POST]::/refunds - Content-Type is application/json\", function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
- " \"application/json\",",
- " );",
+ "pm.test(\"[POST]::/payments/:id/confirm - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");",
"});",
"",
"// Set response object as internal variable",
"let jsonData = {};",
- "try {",
- " jsonData = pm.response.json();",
- "} catch (e) {}",
- "",
- "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id",
- "if (jsonData?.refund_id) {",
- " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);",
- " console.log(",
- " \"- use {{refund_id}} as collection variable for value\",",
- " jsonData.refund_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",",
- " );",
- "}",
+ "try {jsonData = pm.response.json();}catch(e){}",
"",
- "// Response body should have value \"succeeded\" for \"status\"",
- "if (jsonData?.status) {",
- " pm.test(",
- " \"[POST]::/refunds - Content check if value for 'status' matches 'pending'\",",
- " function () {",
- " pm.expect(jsonData.status).to.eql(\"pending\");",
- " },",
- " );",
- "}",
+ "// Validate if response has JSON Body ",
+ "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
"",
- "// Response body should have value \"1000\" for \"amount\"",
+ "//// Response body should have value \"processing\" for \"status\"",
"if (jsonData?.status) {",
- " pm.test(",
- " \"[POST]::/refunds - Content check if value for 'amount' matches '10'\",",
- " function () {",
- " pm.expect(jsonData.amount).to.eql(10);",
- " },",
- " );",
- "}",
+ "pm.test(\"[POST]::/payments - Content check if value for 'status' matches 'processing'\", function() {",
+ " pm.expect(jsonData.status).to.eql(\"processing\");",
+ "})};",
+ "",
+ "",
+ "// Check if the 'amount' is equal to \"amount\"",
+ "pm.test(\"[POST]::/payments/:id -Content Check if 'amount' matches '{{amount}}' \", function () {",
+ " pm.expect(jsonData.amount).to.eql(amount);",
+ "});",
+ "",
+ "//// Response body should have value \"amount_received\" for \"amount\"",
+ "if (jsonData?.amount_received) {",
+ "pm.test(\"[POST]::/payments - Content check if value for 'amount_received' matches '{{amount}}'\", function() {",
+ " pm.expect(jsonData.amount_received).to.eql(amount);",
+ "})};",
""
],
"type": "text/javascript"
@@ -6072,6 +6025,26 @@
}
],
"request": {
+ "auth": {
+ "type": "apikey",
+ "apikey": [
+ {
+ "key": "value",
+ "value": "{{publishable_key}}",
+ "type": "string"
+ },
+ {
+ "key": "key",
+ "value": "api-key",
+ "type": "string"
+ },
+ {
+ "key": "in",
+ "value": "header",
+ "type": "string"
+ }
+ ]
+ },
"method": "POST",
"header": [
{
@@ -6081,6 +6054,12 @@
{
"key": "Accept",
"value": "application/json"
+ },
+ {
+ "key": "publishable_key",
+ "value": "",
+ "type": "text",
+ "disabled": true
}
],
"body": {
@@ -6090,78 +6069,109 @@
"language": "json"
}
},
- "raw": "{\"payment_id\":\"{{payment_id}}\",\"amount\":10,\"reason\":\"Customer returned product\",\"refund_type\":\"instant\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
+ "raw": "{\"client_secret\":\"{{client_secret}}\",\"payment_method\":\"card\",\"payment_method_type\":\"debit\",\"payment_method_data\":{\"card\":{\"card_number\":\"4111111111111111\",\"card_exp_month\":\"03\",\"card_exp_year\":\"69\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"737\"}},\"setup_future_usage\":\"on_session\",\"customer_acceptance\":{\"acceptance_type\":\"online\",\"accepted_at\":\"2022-09-10T10:11:12Z\",\"online\":{\"ip_address\":\"123.32.25.123\",\"user_agent\":\"Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36\"}},\"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\":\"128.0.0.1\"}}"
},
"url": {
- "raw": "{{baseUrl}}/refunds",
+ "raw": "{{baseUrl}}/payments/:id/confirm",
"host": [
"{{baseUrl}}"
],
"path": [
- "refunds"
+ "payments",
+ ":id",
+ "confirm"
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}"
+ }
]
},
- "description": "To create a refund against an already processed payment"
+ "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API"
},
"response": []
},
{
- "name": "Refunds - Retrieve-copy",
+ "name": "Payments - Retrieve",
"event": [
+ {
+ "listen": "prerequest",
+ "script": {
+ "exec": [
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ },
{
"listen": "test",
"script": {
"exec": [
- "// Validate status 2xx",
- "pm.test(\"[GET]::/refunds/:id - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
+ "// Get the value of 'amount' from the environment",
+ "const amount = pm.environment.get(\"amount\");",
+ "",
+ "// Validate status 2xx ",
+ "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
- "pm.test(\"[GET]::/refunds/:id - Content-Type is application/json\", function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
- " \"application/json\",",
- " );",
+ "pm.test(\"[GET]::/payments/:id - 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(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
"});",
"",
"// Set response object as internal variable",
"let jsonData = {};",
- "try {",
- " jsonData = pm.response.json();",
- "} catch (e) {}",
+ "try {jsonData = pm.response.json();}catch(e){}",
"",
- "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id",
- "if (jsonData?.refund_id) {",
- " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);",
- " console.log(",
- " \"- use {{refund_id}} as collection variable for value\",",
- " jsonData.refund_id,",
- " );",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);",
"} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",",
- " );",
- "}",
+ " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');",
+ "};",
"",
- "// Response body should have value \"succeeded\" for \"status\"",
- "if (jsonData?.status) {",
- " pm.test(",
- " \"[POST]::/refunds - Content check if value for 'status' matches 'succeeded'\",",
- " function () {",
- " pm.expect(jsonData.status).to.eql(\"succeeded\");",
- " },",
- " );",
- "}",
"",
- "// Response body should have value \"6540\" for \"amount\"",
+ "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
+ "if (jsonData?.mandate_id) {",
+ " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');",
+ "};",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');",
+ "};",
+ "",
+ "//// Response body should have value \"requires_capture\" for \"status\"",
"if (jsonData?.status) {",
- " pm.test(",
- " \"[POST]::/refunds - Content check if value for 'amount' matches '10'\",",
- " function () {",
- " pm.expect(jsonData.amount).to.eql(10);",
- " },",
- " );",
- "}",
+ "pm.test(\"[POST]::/payments - Content check if value for 'status' matches 'requires_capture'\", function() {",
+ " pm.expect(jsonData.status).to.eql(\"requires_capture\");",
+ "})};",
+ "",
+ "",
+ "// Check if the 'amount' is equal to \"amount\"",
+ "pm.test(\"[POST]::/payments/:id -Content Check if 'amount' matches '{{amount}}' \", function () {",
+ " pm.expect(jsonData.amount).to.eql(amount);",
+ "});",
+ "",
+ "//// Response body should have value \"amount_received\" for \"amount\"",
+ "if (jsonData?.amount_received) {",
+ "pm.test(\"[POST]::/payments - Content check if value for 'amount_received' matches '{{amount}}'\", function() {",
+ " pm.expect(jsonData.amount_received).to.eql(amount);",
+ "})};",
""
],
"type": "text/javascript"
@@ -6177,47 +6187,68 @@
}
],
"url": {
- "raw": "{{baseUrl}}/refunds/:id",
+ "raw": "{{baseUrl}}/payments/:id?force_sync=true",
"host": [
"{{baseUrl}}"
],
"path": [
- "refunds",
+ "payments",
":id"
],
+ "query": [
+ {
+ "key": "force_sync",
+ "value": "true"
+ }
+ ],
"variable": [
{
"key": "id",
- "value": "{{refund_id}}",
- "description": "(Required) unique refund id"
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
}
]
},
- "description": "To retrieve the properties of a Refund. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
},
"response": []
},
{
- "name": "Payments - Retrieve-copy",
+ "name": "Payments - Capture",
"event": [
+ {
+ "listen": "prerequest",
+ "script": {
+ "exec": [
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ },
{
"listen": "test",
"script": {
"exec": [
+ "// Get the value of 'amount' from the environment",
+ "const amount = pm.environment.get(\"amount\");",
+ "",
"// Validate status 2xx",
- "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
+ "pm.test(\"[POST]::/payments/:id/capture - Status code is 2xx\", function () {",
" pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
- "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
- " \"application/json\",",
- " );",
- "});",
+ "pm.test(",
+ " \"[POST]::/payments/:id/capture - 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(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
+ "pm.test(\"[POST]::/payments/:id/capture - Response has JSON Body\", function () {",
" pm.response.to.have.jsonBody();",
"});",
"",
@@ -6266,39 +6297,188 @@
" );",
"}",
"",
- "// Response body should have value \"Succeeded\" for \"status\"",
+ "// Response body should have value \"processing\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",",
+ " \"[POST]:://payments/:id/capture - Content check if value for 'status' matches 'processing'\",",
" function () {",
- " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " pm.expect(jsonData.status).to.eql(\"processing\");",
" },",
" );",
"}",
"",
- "// Response body should have \"refunds\"",
- "pm.test(\"[POST]::/payments - Content check if 'refunds' exists\", function () {",
- " pm.expect(typeof jsonData.refunds !== \"undefined\").to.be.true;",
+ "// Validate the connector",
+ "pm.test(\"[POST]::/payments - connector\", function () {",
+ " pm.expect(jsonData.connector).to.eql(\"nmi\");",
"});",
- ""
- ],
- "type": "text/javascript"
- }
- }
- ],
- "request": {
- "method": "GET",
- "header": [
- {
- "key": "Accept",
- "value": "application/json"
- }
- ],
- "url": {
- "raw": "{{baseUrl}}/payments/:id?force_sync=true",
- "host": [
- "{{baseUrl}}"
- ],
+ "",
+ "// Response body should have value \"amount\" for \"amount_received\"",
+ "if (jsonData?.amount_received) {",
+ " pm.test(",
+ " \"[POST]::/payments:id/capture - Content check if value for 'amount_received' matches '{{amount}}'\",",
+ " function () {",
+ " pm.expect(jsonData.amount_received).to.eql(amount);",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"0\" for \"amount_capturable\"",
+ "if (jsonData?.amount_capturable) {",
+ " pm.test(",
+ " \"[post]:://payments/:id/capture - Content check if value for 'amount_capturable' matches 'amount - 0'\",",
+ " function () {",
+ " pm.expect(jsonData.amount_capturable).to.eql(amount);",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount_to_capture\":\"{{amount}}\",\"statement_descriptor_name\":\"Joseph\",\"statement_descriptor_suffix\":\"JS\"}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id/capture",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id",
+ "capture"
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "To capture the funds for an uncaptured payment"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Retrieve Copy",
+ "event": [
+ {
+ "listen": "prerequest",
+ "script": {
+ "exec": [
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ },
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Get the value of 'amount' from the environment",
+ "const amount = pm.environment.get(\"amount\");",
+ "",
+ "// Validate status 2xx ",
+ "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/payments/:id - 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(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {jsonData = pm.response.json();}catch(e){}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');",
+ "};",
+ "",
+ "",
+ "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
+ "if (jsonData?.mandate_id) {",
+ " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');",
+ "};",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');",
+ "};",
+ "",
+ "//// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ "pm.test(\"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\", function() {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ "})};",
+ "",
+ "",
+ "// Check if the 'amount' is equal to \"amount\"",
+ "pm.test(\"[POST]::/payments/:id -Content Check if 'amount' matches '{{amount}}' \", function () {",
+ " pm.expect(jsonData.amount).to.eql(amount);",
+ "});",
+ "",
+ "//// Response body should have value \"amount_received\" for \"amount\"",
+ "if (jsonData?.amount_received) {",
+ "pm.test(\"[POST]::/payments - Content check if value for 'amount_received' matches '{{amount}}'\", function() {",
+ " pm.expect(jsonData.amount_received).to.eql(amount);",
+ "})};",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id?force_sync=true",
+ "host": [
+ "{{baseUrl}}"
+ ],
"path": [
"payments",
":id"
@@ -6324,7 +6504,7 @@
]
},
{
- "name": "Scenario8-Create a failure card payment with confirm true",
+ "name": "Scenario10-Create a mandate and recurring payment",
"item": [
{
"name": "Payments - Create",
@@ -6333,7 +6513,7 @@
"listen": "prerequest",
"script": {
"exec": [
- "pm.environment.set(\"random_number\", _.random(1000, 100000));",
+ "pm.environment.set(\"random_number\", _.random(100, 100000));",
""
],
"type": "text/javascript"
@@ -6405,44 +6585,31 @@
" );",
"}",
"",
- "// Response body should have value \"succeeded\" for \"status\"",
+ "// Response body should have value \"processing\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments - Content check if value for 'status' matches 'failed'\",",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'processing'\",",
" function () {",
- " pm.expect(jsonData.status).to.eql(\"failed\");",
+ " pm.expect(jsonData.status).to.eql(\"processing\");",
" },",
" );",
"}",
"",
- "// Response body should have \"connector_transaction_id\"",
+ "// Response body should have \"mandate_id\"",
"pm.test(",
- " \"[POST]::/payments - Content check if 'connector_transaction_id' exists\",",
+ " \"[POST]::/payments - Content check if 'mandate_id' exists\",",
" function () {",
- " pm.expect(typeof jsonData.connector_transaction_id !== \"undefined\").to.be",
- " .true;",
+ " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;",
" },",
");",
"",
- "// Response body should have value \"200\" for \"error_code\"",
- "if (jsonData?.error_code) {",
- " pm.test(",
- " \"[POST]::/payments/:id/confirm - Content check if value for 'error_code' matches '200'\",",
- " function () {",
- " pm.expect(jsonData.error_code).to.eql(\"200\");",
- " },",
- " );",
- "}",
- "",
- "// Response body should have value \"message - DECLINE\"",
- "if (jsonData?.error_message) {",
- " pm.test(",
- " \"[POST]::/payments/:id/confirm - Content check if value for 'error_message' matches 'DECLINE'\",",
- " function () {",
- " pm.expect(jsonData.error_message).to.eql(\"DECLINE\");",
- " },",
- " );",
- "}",
+ "// Response body should have \"mandate_data\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_data' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;",
+ " },",
+ ");",
""
],
"type": "text/javascript"
@@ -6468,7 +6635,7 @@
"language": "json"
}
},
- "raw": "{\"amount\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":true,\"business_country\":\"US\",\"business_label\":\"default\",\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"customer_id\":\"bernard123\",\"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://duck.com\",\"setup_future_usage\":\"on_session\",\"customer_acceptance\":{\"acceptance_type\":\"online\",\"accepted_at\":\"2022-09-10T10:11:12Z\",\"online\":{\"ip_address\":\"123.32.25.123\",\"user_agent\":\"Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36\"}},\"payment_method\":\"card\",\"payment_method_type\":\"debit\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"01\",\"card_exp_year\":\"26\",\"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\":\"John\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\",\"last_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
+ "raw": "{\"amount\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"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://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4111111111111111\",\"card_exp_month\":\"10\",\"card_exp_year\":\"69\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"setup_future_usage\":\"off_session\",\"mandate_data\":{\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"127.0.0.1\",\"user_agent\":\"amet irure esse\"}},\"mandate_type\":{\"single_use\":{\"amount\":100000,\"currency\":\"USD\"}}},\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"127.0.0.1\",\"user_agent\":\"amet irure esse\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
},
"url": {
"raw": "{{baseUrl}}/payments",
@@ -6486,15 +6653,6 @@
{
"name": "Payments - Retrieve",
"event": [
- {
- "listen": "prerequest",
- "script": {
- "exec": [
- ""
- ],
- "type": "text/javascript"
- }
- },
{
"listen": "test",
"script": {
@@ -6564,45 +6722,32 @@
"// Response body should have value \"Succeeded\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments/:id - Content check if value for 'status' matches 'failed'\",",
+ " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",",
" function () {",
- " pm.expect(jsonData.status).to.eql(\"failed\");",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
" },",
" );",
"}",
"",
- "// Response body should have \"connector_transaction_id\"",
+ "// Response body should have \"mandate_id\"",
"pm.test(",
- " \"[POST]::/payments - Content check if 'connector_transaction_id' exists\",",
+ " \"[POST]::/payments - Content check if 'mandate_id' exists\",",
" function () {",
- " pm.expect(typeof jsonData.connector_transaction_id !== \"undefined\").to.be",
- " .true;",
+ " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;",
" },",
");",
"",
- "// Response body should have value \"200\" for \"error_code\"",
- "if (jsonData?.error_code) {",
- " pm.test(",
- " \"[POST]::/payments/:id/confirm - Content check if value for 'error_code' matches '200'\",",
- " function () {",
- " pm.expect(jsonData.error_code).to.eql(\"200\");",
- " },",
- " );",
- "}",
- "",
- "// Response body should have value \"message - DECLINE\"",
- "if (jsonData?.error_message) {",
- " pm.test(",
- " \"[POST]::/payments/:id/confirm - Content check if value for 'error_message' matches 'DECLINE'\",",
- " function () {",
- " pm.expect(jsonData.error_message).to.eql(\"DECLINE\");",
- " },",
- " );",
- "}",
- ""
- ],
- "type": "text/javascript"
- }
+ "// Response body should have \"mandate_data\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_data' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ ""
+ ],
+ "type": "text/javascript"
+ }
}
],
"request": {
@@ -6639,20 +6784,15 @@
"description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
},
"response": []
- }
- ]
- },
- {
- "name": "Scenario9-Update amount with automatic capture",
- "item": [
+ },
{
- "name": "Payments - Create",
+ "name": "Recurring Payments - Create",
"event": [
{
"listen": "prerequest",
"script": {
"exec": [
- "pm.environment.set(\"random_number\", _.random(1000, 100000));",
+ "pm.environment.set(\"random_number\", _.random(100, 100000));",
""
],
"type": "text/javascript"
@@ -6662,256 +6802,101 @@
"listen": "test",
"script": {
"exec": [
- "// Set the environment variable 'amount' with the value from the response",
- "pm.environment.set(\"amount\", pm.response.json().amount);",
- "",
- "// Validate status 2xx ",
+ "// Validate status 2xx",
"pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
+ " pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
"pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
"});",
"",
- "// Validate if response has JSON Body ",
+ "// Validate if response has JSON Body",
"pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
- " pm.response.to.have.jsonBody();",
+ " pm.response.to.have.jsonBody();",
"});",
"",
"// Set response object as internal variable",
"let jsonData = {};",
- "try {jsonData = pm.response.json();}catch(e){}",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
"",
"// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
"if (jsonData?.payment_id) {",
- " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
- " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
"} else {",
- " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');",
- "};",
- "",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
"",
"// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
"if (jsonData?.mandate_id) {",
- " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
- " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);",
+ " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ " console.log(",
+ " \"- use {{mandate_id}} as collection variable for value\",",
+ " jsonData.mandate_id,",
+ " );",
"} else {",
- " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');",
- "};",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
+ " );",
+ "}",
"",
"// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
"if (jsonData?.client_secret) {",
- " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
- " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);",
- "} else {",
- " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');",
- "};",
- "",
- "// pm.collectionVariables - Set customer_id as variable for jsonData.customer_id",
- "if (jsonData?.customer_id) {",
- " pm.collectionVariables.set(\"customer_id\", jsonData.customer_id);",
- " console.log(\"- use {{customer_id}} as collection variable for value\",jsonData.customer_id);",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
"} else {",
- " console.log('INFO - Unable to assign variable {{customer_id}}, as jsonData.customer_id is undefined.');",
- "};",
- "// Response body should have value \"requires_payment_method\" for \"status\"",
- "if (jsonData?.status) {",
- "pm.test(\"[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'\", function() {",
- " pm.expect(jsonData.status).to.eql(\"requires_payment_method\");",
- "})};",
- ""
- ],
- "type": "text/javascript"
- }
- }
- ],
- "request": {
- "method": "POST",
- "header": [
- {
- "key": "Content-Type",
- "value": "application/json"
- },
- {
- "key": "Accept",
- "value": "application/json"
- }
- ],
- "body": {
- "mode": "raw",
- "options": {
- "raw": {
- "language": "json"
- }
- },
- "raw": "{\"amount\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"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://duck.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
- },
- "url": {
- "raw": "{{baseUrl}}/payments",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments"
- ]
- },
- "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
- },
- "response": []
- },
- {
- "name": "Payments - Update",
- "event": [
- {
- "listen": "prerequest",
- "script": {
- "exec": [
- "// Get the value of 'amount' from the environment",
- "pm.environment.set(\"another_random_number\", _.random(100, 100000));",
- ""
- ],
- "type": "text/javascript"
- }
- },
- {
- "listen": "test",
- "script": {
- "exec": [
- "// Set the environment variable 'amount' with the value from the response",
- "pm.environment.set(\"amount\", pm.response.json().amount);",
- "",
- "// Get the value of 'amount' from the environment",
- "const updated_amount = pm.environment.get(\"amount\");",
- "",
- "// Validate status 2xx ",
- "pm.test(\"[POST]::/payments/:id - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
- "});",
- "",
- "// Validate if response header has matching content-type",
- "pm.test(\"[POST]::/payments/:id - 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]::/payments/:id - Response has JSON Body\", function () {",
- " pm.response.to.have.jsonBody();",
- "});",
- "",
- "",
- "// Parse the JSON response",
- "var jsonData = pm.response.json();",
- "",
- "// Check if the 'amount' is equal to \"updated_amount\"",
- "pm.test(\"[POST]::/payments/:id -Content Check if 'amount' matches '{{updated_amount}}'\", function () {",
- " pm.expect(jsonData.amount).to.eql(updated_amount);",
- "});",
- "",
- "",
- ""
- ],
- "type": "text/javascript"
- }
- }
- ],
- "request": {
- "method": "POST",
- "header": [
- {
- "key": "Content-Type",
- "value": "application/json"
- },
- {
- "key": "Accept",
- "value": "application/json"
- }
- ],
- "body": {
- "mode": "raw",
- "options": {
- "raw": {
- "language": "json"
- }
- },
- "raw": "{\"amount\":\"{{another_random_number}}\",\"amount_to_capture\":\"{{another_random_number}}\"}"
- },
- "url": {
- "raw": "{{baseUrl}}/payments/:id",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments",
- ":id"
- ],
- "variable": [
- {
- "key": "id",
- "value": "{{payment_id}}"
- }
- ]
- },
- "description": "To update the properties of a PaymentIntent object. This may include attaching a payment method, or attaching customer object or metadata fields after the Payment is created "
- },
- "response": []
- },
- {
- "name": "Payments - Confirm",
- "event": [
- {
- "listen": "prerequest",
- "script": {
- "exec": [
- ""
- ],
- "type": "text/javascript"
- }
- },
- {
- "listen": "test",
- "script": {
- "exec": [
- "// Get the value of 'amount' from the environment",
- "const amount = pm.environment.get(\"amount\");",
- "",
- "// Validate status 2xx ",
- "pm.test(\"[POST]::/payments/:id/confirm - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
- "});",
- "",
- "// Validate if response header has matching content-type",
- "pm.test(\"[POST]::/payments/:id/confirm - Content-Type is application/json\", function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");",
- "});",
- "",
- "// Set response object as internal variable",
- "let jsonData = {};",
- "try {jsonData = pm.response.json();}catch(e){}",
- "",
- "// Validate if response has JSON Body ",
- "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {",
- " pm.response.to.have.jsonBody();",
- "});",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
"",
- "//// Response body should have value \"processing\" for \"status\"",
+ "// Response body should have value \"processing\" for \"status\"",
"if (jsonData?.status) {",
- "pm.test(\"[POST]::/payments - Content check if value for 'status' matches 'processing'\", function() {",
- " pm.expect(jsonData.status).to.eql(\"processing\");",
- "})};",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'processing'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"processing\");",
+ " },",
+ " );",
+ "}",
"",
+ "// Response body should have \"mandate_id\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_id' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;",
+ " },",
+ ");",
"",
- "// Check if the 'amount' is equal to \"amount\"",
- "pm.test(\"[POST]::/payments/:id -Content Check if 'amount' matches '{{amount}}' \", function () {",
- " pm.expect(jsonData.amount).to.eql(amount);",
- "});",
+ "// Response body should have \"mandate_data\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_data' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;",
+ " },",
+ ");",
"",
- "//// Response body should have value \"amount_received\" for \"amount\"",
- "if (jsonData?.amount_received) {",
- "pm.test(\"[POST]::/payments - Content check if value for 'amount_received' matches '{{amount}}'\", function() {",
- " pm.expect(jsonData.amount_received).to.eql(amount);",
- "})};",
+ "// Response body should have \"payment_method_data\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'payment_method_data' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.payment_method_data !== \"undefined\").to.be.true;",
+ " },",
+ ");",
""
],
"type": "text/javascript"
@@ -6919,26 +6904,6 @@
}
],
"request": {
- "auth": {
- "type": "apikey",
- "apikey": [
- {
- "key": "value",
- "value": "{{publishable_key}}",
- "type": "string"
- },
- {
- "key": "key",
- "value": "api-key",
- "type": "string"
- },
- {
- "key": "in",
- "value": "header",
- "type": "string"
- }
- ]
- },
"method": "POST",
"header": [
{
@@ -6948,12 +6913,6 @@
{
"key": "Accept",
"value": "application/json"
- },
- {
- "key": "publishable_key",
- "value": "",
- "type": "text",
- "disabled": true
}
],
"body": {
@@ -6963,109 +6922,115 @@
"language": "json"
}
},
- "raw": "{\"client_secret\":\"{{client_secret}}\",\"payment_method\":\"card\",\"payment_method_type\":\"debit\",\"payment_method_data\":{\"card\":{\"card_number\":\"4111111111111111\",\"card_exp_month\":\"03\",\"card_exp_year\":\"69\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"737\"}},\"setup_future_usage\":\"on_session\",\"customer_acceptance\":{\"acceptance_type\":\"online\",\"accepted_at\":\"2022-09-10T10:11:12Z\",\"online\":{\"ip_address\":\"123.32.25.123\",\"user_agent\":\"Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36\"}},\"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\":\"128.0.0.1\"}}"
+ "raw": "{\"amount\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"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://duck.com\",\"mandate_id\":\"{{mandate_id}}\",\"off_session\":true,\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
},
"url": {
- "raw": "{{baseUrl}}/payments/:id/confirm",
+ "raw": "{{baseUrl}}/payments",
"host": [
"{{baseUrl}}"
],
"path": [
- "payments",
- ":id",
- "confirm"
- ],
- "variable": [
- {
- "key": "id",
- "value": "{{payment_id}}"
- }
+ "payments"
]
},
- "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API"
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
},
"response": []
},
{
- "name": "Payments - Retrieve",
+ "name": "Payments - Retrieve-copy",
"event": [
- {
- "listen": "prerequest",
- "script": {
- "exec": [
- ""
- ],
- "type": "text/javascript"
- }
- },
{
"listen": "test",
"script": {
"exec": [
- "// Get the value of 'amount' from the environment",
- "const amount = pm.environment.get(\"amount\");",
- "",
- "// Validate status 2xx ",
+ "// Validate status 2xx",
"pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
+ " pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
"pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
"});",
"",
- "// Validate if response has JSON Body ",
+ "// Validate if response has JSON Body",
"pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
- " pm.response.to.have.jsonBody();",
+ " pm.response.to.have.jsonBody();",
"});",
"",
"// Set response object as internal variable",
"let jsonData = {};",
- "try {jsonData = pm.response.json();}catch(e){}",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
"",
"// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
"if (jsonData?.payment_id) {",
- " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
- " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
"} else {",
- " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');",
- "};",
- "",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
"",
"// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
"if (jsonData?.mandate_id) {",
- " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
- " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);",
+ " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ " console.log(",
+ " \"- use {{mandate_id}} as collection variable for value\",",
+ " jsonData.mandate_id,",
+ " );",
"} else {",
- " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');",
- "};",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
+ " );",
+ "}",
"",
"// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
"if (jsonData?.client_secret) {",
- " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
- " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
"} else {",
- " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');",
- "};",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
"",
- "//// Response body should have value \"succeeded\" for \"status\"",
+ "// Response body should have value \"Succeeded\" for \"status\"",
"if (jsonData?.status) {",
- "pm.test(\"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\", function() {",
- " pm.expect(jsonData.status).to.eql(\"succeeded\");",
- "})};",
- "",
+ " pm.test(",
+ " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
"",
- "// Check if the 'amount' is equal to \"amount\"",
- "pm.test(\"[POST]::/payments/:id -Content Check if 'amount' matches '{{amount}}' \", function () {",
- " pm.expect(jsonData.amount).to.eql(amount);",
- "});",
+ "// Response body should have \"mandate_id\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_id' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;",
+ " },",
+ ");",
"",
- "//// Response body should have value \"amount_received\" for \"amount\"",
- "if (jsonData?.amount_received) {",
- "pm.test(\"[POST]::/payments - Content check if value for 'amount_received' matches '{{amount}}'\", function() {",
- " pm.expect(jsonData.amount_received).to.eql(amount);",
- "})};",
+ "// Response body should have \"mandate_data\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_data' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;",
+ " },",
+ ");",
""
],
"type": "text/javascript"
@@ -7110,7 +7075,7 @@
]
},
{
- "name": "Scenario9a-Update amount with manual capture",
+ "name": "Scenario11-Refund recurring payment",
"item": [
{
"name": "Payments - Create",
@@ -7132,62 +7097,93 @@
"// Set the environment variable 'amount' with the value from the response",
"pm.environment.set(\"amount\", pm.response.json().amount);",
"",
- "// Validate status 2xx ",
+ "// Validate status 2xx",
"pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
+ " pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
"pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
"});",
"",
- "// Validate if response has JSON Body ",
+ "// Validate if response has JSON Body",
"pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
- " pm.response.to.have.jsonBody();",
+ " pm.response.to.have.jsonBody();",
"});",
"",
"// Set response object as internal variable",
"let jsonData = {};",
- "try {jsonData = pm.response.json();}catch(e){}",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
"",
"// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
"if (jsonData?.payment_id) {",
- " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
- " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
"} else {",
- " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');",
- "};",
- "",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
"",
"// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
"if (jsonData?.mandate_id) {",
- " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
- " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);",
+ " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ " console.log(",
+ " \"- use {{mandate_id}} as collection variable for value\",",
+ " jsonData.mandate_id,",
+ " );",
"} else {",
- " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');",
- "};",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
+ " );",
+ "}",
"",
"// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
"if (jsonData?.client_secret) {",
- " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
- " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
"} else {",
- " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');",
- "};",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
"",
- "// pm.collectionVariables - Set customer_id as variable for jsonData.customer_id",
- "if (jsonData?.customer_id) {",
- " pm.collectionVariables.set(\"customer_id\", jsonData.customer_id);",
- " console.log(\"- use {{customer_id}} as collection variable for value\",jsonData.customer_id);",
- "} else {",
- " console.log('INFO - Unable to assign variable {{customer_id}}, as jsonData.customer_id is undefined.');",
- "};",
- "// Response body should have value \"requires_payment_method\" for \"status\"",
+ "// Response body should have value \"processing\" for \"status\"",
"if (jsonData?.status) {",
- "pm.test(\"[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'\", function() {",
- " pm.expect(jsonData.status).to.eql(\"requires_payment_method\");",
- "})};",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'processing'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"processing\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have \"mandate_id\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_id' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ "",
+ "// Response body should have \"mandate_data\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_data' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;",
+ " },",
+ ");",
""
],
"type": "text/javascript"
@@ -7213,7 +7209,7 @@
"language": "json"
}
},
- "raw": "{\"amount\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"manual\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"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://duck.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
+ "raw": "{\"amount\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"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://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4111111111111111\",\"card_exp_month\":\"10\",\"card_exp_year\":\"69\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"setup_future_usage\":\"off_session\",\"mandate_data\":{\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"127.0.0.1\",\"user_agent\":\"amet irure esse\"}},\"mandate_type\":{\"single_use\":{\"amount\":100000,\"currency\":\"USD\"}}},\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"127.0.0.1\",\"user_agent\":\"amet irure esse\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
},
"url": {
"raw": "{{baseUrl}}/payments",
@@ -7229,54 +7225,99 @@
"response": []
},
{
- "name": "Payments - Update",
+ "name": "Payments - Retrieve",
"event": [
- {
- "listen": "prerequest",
- "script": {
- "exec": [
- "// Get the value of 'amount' from the environment",
- "pm.environment.set(\"another_random_number\", _.random(100, 100000));",
- ""
- ],
- "type": "text/javascript"
- }
- },
{
"listen": "test",
"script": {
"exec": [
- "// Set the environment variable 'amount' with the value from the response",
- "pm.environment.set(\"amount\", pm.response.json().amount);",
- "",
- "// Get the value of 'amount' from the environment",
- "const updated_amount = pm.environment.get(\"amount\");",
- "",
- "// Validate status 2xx ",
- "pm.test(\"[POST]::/payments/:id - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
+ "// Validate status 2xx",
+ "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
- "pm.test(\"[POST]::/payments/:id - Content-Type is application/json\", function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");",
+ "pm.test(\"[GET]::/payments/:id - 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]::/payments/:id - Response has JSON Body\", function () {",
- " pm.response.to.have.jsonBody();",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
"});",
"",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
"",
- "// Parse the JSON response",
- "var jsonData = pm.response.json();",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
"",
- "// Check if the 'amount' is equal to \"updated_amount\"",
- "pm.test(\"[POST]::/payments/:id -Content Check if 'amount' matches '{{updated_amount}}'\", function () {",
- " pm.expect(jsonData.amount).to.eql(updated_amount);",
- "});",
+ "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
+ "if (jsonData?.mandate_id) {",
+ " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ " console.log(",
+ " \"- use {{mandate_id}} as collection variable for value\",",
+ " jsonData.mandate_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"Succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
"",
+ "// Response body should have \"mandate_id\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_id' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;",
+ " },",
+ ");",
"",
+ "// Response body should have \"mandate_data\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_data' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;",
+ " },",
+ ");",
""
],
"type": "text/javascript"
@@ -7284,28 +7325,15 @@
}
],
"request": {
- "method": "POST",
+ "method": "GET",
"header": [
- {
- "key": "Content-Type",
- "value": "application/json"
- },
{
"key": "Accept",
"value": "application/json"
}
],
- "body": {
- "mode": "raw",
- "options": {
- "raw": {
- "language": "json"
- }
- },
- "raw": "{\"amount\":\"{{another_random_number}}\",\"amount_to_capture\":\"{{another_random_number}}\"}"
- },
"url": {
- "raw": "{{baseUrl}}/payments/:id",
+ "raw": "{{baseUrl}}/payments/:id?force_sync=true",
"host": [
"{{baseUrl}}"
],
@@ -7313,24 +7341,32 @@
"payments",
":id"
],
+ "query": [
+ {
+ "key": "force_sync",
+ "value": "true"
+ }
+ ],
"variable": [
{
"key": "id",
- "value": "{{payment_id}}"
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
}
]
},
- "description": "To update the properties of a PaymentIntent object. This may include attaching a payment method, or attaching customer object or metadata fields after the Payment is created "
+ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
},
"response": []
},
{
- "name": "Payments - Confirm",
+ "name": "Recurring Payments - Create",
"event": [
{
"listen": "prerequest",
"script": {
"exec": [
+ "pm.environment.set(\"random_number\", _.random(100, 100000));",
""
],
"type": "text/javascript"
@@ -7340,45 +7376,104 @@
"listen": "test",
"script": {
"exec": [
- "// Get the value of 'amount' from the environment",
- "const amount = pm.environment.get(\"amount\");",
+ "// Set the environment variable 'amount' with the value from the response",
+ "pm.environment.set(\"amount\", pm.response.json().amount);",
"",
- "// Validate status 2xx ",
- "pm.test(\"[POST]::/payments/:id/confirm - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
- "pm.test(\"[POST]::/payments/:id/confirm - Content-Type is application/json\", function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");",
+ "pm.test(\"[POST]::/payments - 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]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
"});",
"",
"// Set response object as internal variable",
"let jsonData = {};",
- "try {jsonData = pm.response.json();}catch(e){}",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
"",
- "// Validate if response has JSON Body ",
- "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {",
- " pm.response.to.have.jsonBody();",
- "});",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
"",
- "//// Response body should have value \"processing\" for \"status\"",
+ "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
+ "if (jsonData?.mandate_id) {",
+ " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ " console.log(",
+ " \"- use {{mandate_id}} as collection variable for value\",",
+ " jsonData.mandate_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"processing\" for \"status\"",
"if (jsonData?.status) {",
- "pm.test(\"[POST]::/payments - Content check if value for 'status' matches 'processing'\", function() {",
- " pm.expect(jsonData.status).to.eql(\"processing\");",
- "})};",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'processing'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"processing\");",
+ " },",
+ " );",
+ "}",
"",
+ "// Response body should have \"mandate_id\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_id' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;",
+ " },",
+ ");",
"",
- "// Check if the 'amount' is equal to \"amount\"",
- "pm.test(\"[POST]::/payments/:id -Content Check if 'amount' matches '{{amount}}' \", function () {",
- " pm.expect(jsonData.amount).to.eql(amount);",
- "});",
+ "// Response body should have \"mandate_data\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_data' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;",
+ " },",
+ ");",
"",
- "//// Response body should have value \"amount_received\" for \"amount\"",
- "if (jsonData?.amount_received) {",
- "pm.test(\"[POST]::/payments - Content check if value for 'amount_received' matches '{{amount}}'\", function() {",
- " pm.expect(jsonData.amount_received).to.eql(amount);",
- "})};",
+ "// Response body should have \"payment_method_data\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'payment_method_data' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.payment_method_data !== \"undefined\").to.be.true;",
+ " },",
+ ");",
""
],
"type": "text/javascript"
@@ -7386,26 +7481,6 @@
}
],
"request": {
- "auth": {
- "type": "apikey",
- "apikey": [
- {
- "key": "value",
- "value": "{{publishable_key}}",
- "type": "string"
- },
- {
- "key": "key",
- "value": "api-key",
- "type": "string"
- },
- {
- "key": "in",
- "value": "header",
- "type": "string"
- }
- ]
- },
"method": "POST",
"header": [
{
@@ -7415,12 +7490,6 @@
{
"key": "Accept",
"value": "application/json"
- },
- {
- "key": "publishable_key",
- "value": "",
- "type": "text",
- "disabled": true
}
],
"body": {
@@ -7430,109 +7499,115 @@
"language": "json"
}
},
- "raw": "{\"client_secret\":\"{{client_secret}}\",\"payment_method\":\"card\",\"payment_method_type\":\"debit\",\"payment_method_data\":{\"card\":{\"card_number\":\"4111111111111111\",\"card_exp_month\":\"03\",\"card_exp_year\":\"69\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"737\"}},\"setup_future_usage\":\"on_session\",\"customer_acceptance\":{\"acceptance_type\":\"online\",\"accepted_at\":\"2022-09-10T10:11:12Z\",\"online\":{\"ip_address\":\"123.32.25.123\",\"user_agent\":\"Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36\"}},\"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\":\"128.0.0.1\"}}"
+ "raw": "{\"amount\":\"{{random_number}}\",\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":\"{{random_number}}\",\"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://duck.com\",\"mandate_id\":\"{{mandate_id}}\",\"off_session\":true,\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
},
"url": {
- "raw": "{{baseUrl}}/payments/:id/confirm",
+ "raw": "{{baseUrl}}/payments",
"host": [
"{{baseUrl}}"
],
"path": [
- "payments",
- ":id",
- "confirm"
- ],
- "variable": [
- {
- "key": "id",
- "value": "{{payment_id}}"
- }
+ "payments"
]
},
- "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API"
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
},
"response": []
},
{
- "name": "Payments - Retrieve",
+ "name": "Payments - Retrieve-copy",
"event": [
- {
- "listen": "prerequest",
- "script": {
- "exec": [
- ""
- ],
- "type": "text/javascript"
- }
- },
{
"listen": "test",
"script": {
"exec": [
- "// Get the value of 'amount' from the environment",
- "const amount = pm.environment.get(\"amount\");",
- "",
- "// Validate status 2xx ",
+ "// Validate status 2xx",
"pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
+ " pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
"pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
"});",
"",
- "// Validate if response has JSON Body ",
+ "// Validate if response has JSON Body",
"pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
- " pm.response.to.have.jsonBody();",
+ " pm.response.to.have.jsonBody();",
"});",
"",
"// Set response object as internal variable",
"let jsonData = {};",
- "try {jsonData = pm.response.json();}catch(e){}",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
"",
"// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
"if (jsonData?.payment_id) {",
- " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
- " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
"} else {",
- " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');",
- "};",
- "",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
"",
"// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
"if (jsonData?.mandate_id) {",
- " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
- " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);",
+ " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ " console.log(",
+ " \"- use {{mandate_id}} as collection variable for value\",",
+ " jsonData.mandate_id,",
+ " );",
"} else {",
- " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');",
- "};",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
+ " );",
+ "}",
"",
"// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
"if (jsonData?.client_secret) {",
- " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
- " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
"} else {",
- " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');",
- "};",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
"",
- "//// Response body should have value \"requires_capture\" for \"status\"",
+ "// Response body should have value \"Succeeded\" for \"status\"",
"if (jsonData?.status) {",
- "pm.test(\"[POST]::/payments - Content check if value for 'status' matches 'requires_capture'\", function() {",
- " pm.expect(jsonData.status).to.eql(\"requires_capture\");",
- "})};",
- "",
+ " pm.test(",
+ " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
"",
- "// Check if the 'amount' is equal to \"amount\"",
- "pm.test(\"[POST]::/payments/:id -Content Check if 'amount' matches '{{amount}}' \", function () {",
- " pm.expect(jsonData.amount).to.eql(amount);",
- "});",
+ "// Response body should have \"mandate_id\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_id' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;",
+ " },",
+ ");",
"",
- "//// Response body should have value \"amount_received\" for \"amount\"",
- "if (jsonData?.amount_received) {",
- "pm.test(\"[POST]::/payments - Content check if value for 'amount_received' matches '{{amount}}'\", function() {",
- " pm.expect(jsonData.amount_received).to.eql(amount);",
- "})};",
+ "// Response body should have \"mandate_data\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_data' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;",
+ " },",
+ ");",
""
],
"type": "text/javascript"
@@ -7575,7 +7650,7 @@
"response": []
},
{
- "name": "Payments - Capture",
+ "name": "Refunds - Create",
"event": [
{
"listen": "prerequest",
@@ -7594,23 +7669,15 @@
"const amount = pm.environment.get(\"amount\");",
"",
"// Validate status 2xx",
- "pm.test(\"[POST]::/payments/:id/capture - Status code is 2xx\", function () {",
+ "pm.test(\"[POST]::/refunds - Status code is 2xx\", function () {",
" pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
- "pm.test(",
- " \"[POST]::/payments/:id/capture - 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]::/payments/:id/capture - Response has JSON Body\", function () {",
- " pm.response.to.have.jsonBody();",
+ "pm.test(\"[POST]::/refunds - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
"});",
"",
"// Set response object as internal variable",
@@ -7619,76 +7686,35 @@
" jsonData = pm.response.json();",
"} catch (e) {}",
"",
- "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
- "if (jsonData?.payment_id) {",
- " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
- " console.log(",
- " \"- use {{payment_id}} as collection variable for value\",",
- " jsonData.payment_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
- " );",
- "}",
- "",
- "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
- "if (jsonData?.mandate_id) {",
- " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
- " console.log(",
- " \"- use {{mandate_id}} as collection variable for value\",",
- " jsonData.mandate_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
- " );",
- "}",
- "",
- "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
- "if (jsonData?.client_secret) {",
- " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id",
+ "if (jsonData?.refund_id) {",
+ " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);",
" console.log(",
- " \"- use {{client_secret}} as collection variable for value\",",
- " jsonData.client_secret,",
+ " \"- use {{refund_id}} as collection variable for value\",",
+ " jsonData.refund_id,",
" );",
"} else {",
" console.log(",
- " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",",
" );",
"}",
"",
- "// Response body should have value \"processing\" for \"status\"",
+ "// Response body should have value \"pending\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]:://payments/:id/capture - Content check if value for 'status' matches 'processing'\",",
- " function () {",
- " pm.expect(jsonData.status).to.eql(\"processing\");",
- " },",
- " );",
- "}",
- "",
- "// Validate the connector",
- "pm.test(\"[POST]::/payments - connector\", function () {",
- " pm.expect(jsonData.connector).to.eql(\"nmi\");",
- "});",
- "",
- "// Response body should have value \"amount\" for \"amount_received\"",
- "if (jsonData?.amount_received) {",
- " pm.test(",
- " \"[POST]::/payments:id/capture - Content check if value for 'amount_received' matches '{{amount}}'\",",
+ " \"[POST]::/refunds - Content check if value for 'status' matches 'pending'\",",
" function () {",
- " pm.expect(jsonData.amount_received).to.eql(amount);",
+ " pm.expect(jsonData.status).to.eql(\"pending\");",
" },",
" );",
"}",
"",
- "// Response body should have value \"0\" for \"amount_capturable\"",
- "if (jsonData?.amount_capturable) {",
+ "// Response body should have value for \"amount\"",
+ "if (jsonData?.status) {",
" pm.test(",
- " \"[post]:://payments/:id/capture - Content check if value for 'amount_capturable' matches 'amount - 0'\",",
+ " \"[POST]::/refunds - Content check if value for 'amount' matches '{{amount}}'\",",
" function () {",
- " pm.expect(jsonData.amount_capturable).to.eql(amount);",
+ " pm.expect(jsonData.amount).to.eql(amount);",
" },",
" );",
"}",
@@ -7717,32 +7743,23 @@
"language": "json"
}
},
- "raw": "{\"amount_to_capture\":\"{{amount}}\",\"statement_descriptor_name\":\"Joseph\",\"statement_descriptor_suffix\":\"JS\"}"
+ "raw": "{\"payment_id\":\"{{payment_id}}\",\"amount\":\"{{amount}}\",\"reason\":\"Customer returned product\",\"refund_type\":\"instant\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
},
"url": {
- "raw": "{{baseUrl}}/payments/:id/capture",
+ "raw": "{{baseUrl}}/refunds",
"host": [
"{{baseUrl}}"
],
"path": [
- "payments",
- ":id",
- "capture"
- ],
- "variable": [
- {
- "key": "id",
- "value": "{{payment_id}}",
- "description": "(Required) unique payment id"
- }
+ "refunds"
]
},
- "description": "To capture the funds for an uncaptured payment"
+ "description": "To create a refund against an already processed payment"
},
"response": []
},
{
- "name": "Payments - Retrieve Copy",
+ "name": "Refunds - Retrieve",
"event": [
{
"listen": "prerequest",
@@ -7758,69 +7775,58 @@
"script": {
"exec": [
"// Get the value of 'amount' from the environment",
- "const amount = pm.environment.get(\"amount\");",
+ "const refund_amount = pm.environment.get(\"amount\");",
"",
- "// Validate status 2xx ",
- "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
+ "// Validate status 2xx",
+ "pm.test(\"[GET]::/refunds/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
- "pm.test(\"[GET]::/payments/:id - 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(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
- " pm.response.to.have.jsonBody();",
+ "pm.test(\"[GET]::/refunds/:id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
"});",
"",
"// Set response object as internal variable",
"let jsonData = {};",
- "try {jsonData = pm.response.json();}catch(e){}",
- "",
- "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
- "if (jsonData?.payment_id) {",
- " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
- " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);",
- "} else {",
- " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');",
- "};",
- "",
- "",
- "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
- "if (jsonData?.mandate_id) {",
- " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
- " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);",
- "} else {",
- " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');",
- "};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
"",
- "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
- "if (jsonData?.client_secret) {",
- " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
- " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);",
+ "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id",
+ "if (jsonData?.refund_id) {",
+ " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);",
+ " console.log(",
+ " \"- use {{refund_id}} as collection variable for value\",",
+ " jsonData.refund_id,",
+ " );",
"} else {",
- " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');",
- "};",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",",
+ " );",
+ "}",
"",
- "//// Response body should have value \"succeeded\" for \"status\"",
+ "// Response body should have value \"succeeded\" for \"status\"",
"if (jsonData?.status) {",
- "pm.test(\"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\", function() {",
- " pm.expect(jsonData.status).to.eql(\"succeeded\");",
- "})};",
- "",
- "",
- "// Check if the 'amount' is equal to \"amount\"",
- "pm.test(\"[POST]::/payments/:id -Content Check if 'amount' matches '{{amount}}' \", function () {",
- " pm.expect(jsonData.amount).to.eql(amount);",
- "});",
+ " pm.test(",
+ " \"[POST]::/refunds - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
"",
- "//// Response body should have value \"amount_received\" for \"amount\"",
- "if (jsonData?.amount_received) {",
- "pm.test(\"[POST]::/payments - Content check if value for 'amount_received' matches '{{amount}}'\", function() {",
- " pm.expect(jsonData.amount_received).to.eql(amount);",
- "})};",
+ "// Response body should have value for \"refund_amount\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/refunds - Content check if value for 'refund_amount' matches '{{refund_amount}}'\",",
+ " function () {",
+ " pm.expect(jsonData.amount).to.eql(refund_amount);",
+ " },",
+ " );",
+ "}",
""
],
"type": "text/javascript"
@@ -7836,29 +7842,23 @@
}
],
"url": {
- "raw": "{{baseUrl}}/payments/:id?force_sync=true",
+ "raw": "{{baseUrl}}/refunds/:id",
"host": [
"{{baseUrl}}"
],
"path": [
- "payments",
+ "refunds",
":id"
],
- "query": [
- {
- "key": "force_sync",
- "value": "true"
- }
- ],
"variable": [
{
"key": "id",
- "value": "{{payment_id}}",
- "description": "(Required) unique payment id"
+ "value": "{{refund_id}}",
+ "description": "(Required) unique refund id"
}
]
},
- "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ "description": "To retrieve the properties of a Refund. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
},
"response": []
}
|
2024-03-13T10:26:04Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [x] CI/CD
## Description
<!-- Describe your changes in detail -->
- NMI: Removed `Copy` from `.meta.json` to fix `Scenario 10` an `11` from running before `Scenario 1`
- Bluesnap: Make `customer_id` unique to avoid payment method from being saved
Closes #4070
> [!NOTE]
> `.json` files are auto-generated
### 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)?
-->
- NMI (mandates are failing. @Aprabhat19 is looking into it)
<img width="1240" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/c1493bb8-abc1-4c7b-900a-9910c594ed59">
<img width="1084" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/e3d7e602-891d-4526-9840-ceb41c439dbd">
- Bluesnap
<img width="486" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/52bca980-32a2-43fd-9783-2dcddcc6abdd">
- Checkout
<img width="479" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/532b1bf8-7da0-4ad9-93d8-0a0a730e1852">
Wrote a script:
<img width="575" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/e636435b-5e37-4349-9353-93cf7d6de054">
NMI failed as mentioned above:
<img width="327" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/a19d1e87-61f3-4295-984f-c5aa26681bfa">
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
d82960c1cca5ae43d1a51f8fff6f7b6b9e016c2b
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4026
|
Bug: [REFACTOR] Allow deletion of default payment method for a customer if only one pm exists
Currently, we don't delete the default payment method of a customer. But if only one payment method exists for a customer which is also set to default, then we should allow to delete that payment method
|
diff --git a/crates/diesel_models/src/customers.rs b/crates/diesel_models/src/customers.rs
index cefb0c240ec..bda7af157de 100644
--- a/crates/diesel_models/src/customers.rs
+++ b/crates/diesel_models/src/customers.rs
@@ -52,5 +52,5 @@ pub struct CustomerUpdateInternal {
pub modified_at: Option<PrimitiveDateTime>,
pub connector_customer: Option<serde_json::Value>,
pub address_id: Option<String>,
- pub default_payment_method_id: Option<String>,
+ pub default_payment_method_id: Option<Option<String>>,
}
diff --git a/crates/diesel_models/src/query/generics.rs b/crates/diesel_models/src/query/generics.rs
index 8f2e391df6c..a1dd40cd400 100644
--- a/crates/diesel_models/src/query/generics.rs
+++ b/crates/diesel_models/src/query/generics.rs
@@ -40,6 +40,7 @@ pub mod db_metrics {
DeleteWithResult,
UpdateWithResults,
UpdateOne,
+ Count,
}
#[inline]
diff --git a/crates/diesel_models/src/query/payment_method.rs b/crates/diesel_models/src/query/payment_method.rs
index bed4d079010..a27a2ae8950 100644
--- a/crates/diesel_models/src/query/payment_method.rs
+++ b/crates/diesel_models/src/query/payment_method.rs
@@ -1,4 +1,9 @@
-use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods, Table};
+use async_bb8_diesel::AsyncRunQueryDsl;
+use diesel::{
+ associations::HasTable, debug_query, pg::Pg, BoolExpressionMethods, ExpressionMethods,
+ QueryDsl, Table,
+};
+use error_stack::{IntoReport, ResultExt};
use super::generics;
use crate::{
@@ -96,6 +101,34 @@ impl PaymentMethod {
.await
}
+ pub async fn get_count_by_customer_id_merchant_id_status(
+ conn: &PgPooledConn,
+ customer_id: &str,
+ merchant_id: &str,
+ status: common_enums::PaymentMethodStatus,
+ ) -> StorageResult<i64> {
+ let filter = <Self as HasTable>::table()
+ .count()
+ .filter(
+ dsl::customer_id
+ .eq(customer_id.to_owned())
+ .and(dsl::merchant_id.eq(merchant_id.to_owned()))
+ .and(dsl::status.eq(status.to_owned())),
+ )
+ .into_boxed();
+
+ router_env::logger::debug!(query = %debug_query::<Pg, _>(&filter).to_string());
+
+ generics::db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>(
+ filter.get_result_async::<i64>(conn),
+ generics::db_metrics::DatabaseOperation::Count,
+ )
+ .await
+ .into_report()
+ .change_context(errors::DatabaseError::Others)
+ .attach_printable("Failed to get a count of payment methods")
+ }
+
pub async fn find_by_customer_id_merchant_id_status(
conn: &PgPooledConn,
customer_id: &str,
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index fccacfef45d..ad272860717 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -3193,7 +3193,7 @@ pub async fn set_default_payment_method(
)?;
let customer_update = CustomerUpdate::UpdateDefaultPaymentMethod {
- default_payment_method_id: Some(payment_method_id.to_owned()),
+ default_payment_method_id: Some(Some(payment_method_id.to_owned())),
};
// update the db with the default payment method id
@@ -3442,6 +3442,16 @@ 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,
@@ -3453,7 +3463,8 @@ pub async fn delete_payment_method(
.attach_printable("Customer not found for the payment method")?;
utils::when(
- customer.default_payment_method_id.as_ref() == Some(&pm_id.payment_method_id),
+ customer.default_payment_method_id.as_ref() == Some(&pm_id.payment_method_id)
+ && payment_methods_count > 1,
|| Err(errors::ApiErrorResponse::PaymentMethodDeleteFailed),
)?;
@@ -3481,6 +3492,22 @@ pub async fn delete_payment_method(
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
+ if customer.default_payment_method_id.as_ref() == Some(&pm_id.payment_method_id) {
+ let customer_update = CustomerUpdate::UpdateDefaultPaymentMethod {
+ default_payment_method_id: Some(None),
+ };
+
+ db.update_customer_by_customer_id_merchant_id(
+ key.customer_id,
+ key.merchant_id,
+ customer_update,
+ &key_store,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to update the default payment method id for the customer")?;
+ };
+
Ok(services::ApplicationResponse::Json(
api::PaymentMethodDeleteResponse {
payment_method_id: key.payment_method_id,
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 4509da8f0ff..ff036320098 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -1299,6 +1299,21 @@ impl PaymentMethodInterface for KafkaStore {
.await
}
+ async fn get_payment_method_count_by_customer_id_merchant_id_status(
+ &self,
+ customer_id: &str,
+ merchant_id: &str,
+ status: common_enums::PaymentMethodStatus,
+ ) -> CustomResult<i64, errors::StorageError> {
+ self.diesel_store
+ .get_payment_method_count_by_customer_id_merchant_id_status(
+ customer_id,
+ merchant_id,
+ status,
+ )
+ .await
+ }
+
async fn find_payment_method_by_locker_id(
&self,
locker_id: &str,
diff --git a/crates/router/src/db/payment_method.rs b/crates/router/src/db/payment_method.rs
index ef471fbd246..94ebee17893 100644
--- a/crates/router/src/db/payment_method.rs
+++ b/crates/router/src/db/payment_method.rs
@@ -36,6 +36,13 @@ pub trait PaymentMethodInterface {
limit: Option<i64>,
) -> CustomResult<Vec<storage::PaymentMethod>, errors::StorageError>;
+ async fn get_payment_method_count_by_customer_id_merchant_id_status(
+ &self,
+ customer_id: &str,
+ merchant_id: &str,
+ status: common_enums::PaymentMethodStatus,
+ ) -> CustomResult<i64, errors::StorageError>;
+
async fn insert_payment_method(
&self,
payment_method_new: storage::PaymentMethodNew,
@@ -80,6 +87,25 @@ impl PaymentMethodInterface for Store {
.into_report()
}
+ #[instrument(skip_all)]
+ async fn get_payment_method_count_by_customer_id_merchant_id_status(
+ &self,
+ customer_id: &str,
+ merchant_id: &str,
+ status: common_enums::PaymentMethodStatus,
+ ) -> CustomResult<i64, errors::StorageError> {
+ let conn = connection::pg_connection_read(self).await?;
+ storage::PaymentMethod::get_count_by_customer_id_merchant_id_status(
+ &conn,
+ customer_id,
+ merchant_id,
+ status,
+ )
+ .await
+ .map_err(Into::into)
+ .into_report()
+ }
+
#[instrument(skip_all)]
async fn insert_payment_method(
&self,
@@ -204,6 +230,27 @@ impl PaymentMethodInterface for MockDb {
}
}
+ async fn get_payment_method_count_by_customer_id_merchant_id_status(
+ &self,
+ customer_id: &str,
+ merchant_id: &str,
+ status: common_enums::PaymentMethodStatus,
+ ) -> CustomResult<i64, errors::StorageError> {
+ let payment_methods = self.payment_methods.lock().await;
+ let count = payment_methods
+ .iter()
+ .filter(|pm| {
+ pm.customer_id == customer_id
+ && pm.merchant_id == merchant_id
+ && pm.status == status
+ })
+ .count();
+ count
+ .try_into()
+ .into_report()
+ .change_context(errors::StorageError::MockDbError)
+ }
+
async fn insert_payment_method(
&self,
payment_method_new: storage::PaymentMethodNew,
diff --git a/crates/router/src/types/domain/customer.rs b/crates/router/src/types/domain/customer.rs
index 5437d06a2e6..d5f05944d6c 100644
--- a/crates/router/src/types/domain/customer.rs
+++ b/crates/router/src/types/domain/customer.rs
@@ -118,7 +118,7 @@ pub enum CustomerUpdate {
connector_customer: Option<serde_json::Value>,
},
UpdateDefaultPaymentMethod {
- default_payment_method_id: Option<String>,
+ default_payment_method_id: Option<Option<String>>,
},
}
|
2024-03-08T19:02:18Z
|
## 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, we don't delete the default payment method of a customer. But if only one payment method exists for a customer which is also set to default, then we should allow to delete that payment method
### 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. Store a new card or any other payment method for a customer. (Ensure only one payment method exists for a customer)
2. Set that payment method as default
```
curl --location --request POST 'http://localhost:8080/customers/cus_aXfFGQOFT7JFU47GYhZK/payment_methods/pm_37h7qElY2aTWBEPSgovJ/default' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: abc' \
--data ''
```
3. Now try to delete that default payment method
```
curl --location --request DELETE 'http://localhost:8080/payment_methods/pm_37h7qElY2aTWBEPSgovJ' \
--header 'Accept: application/json' \
--header 'api-key: abc'
```
You should still be able to delete the default payment method as this is the only payment method that exists for that customer.
## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
f5697f372c8e1f27c00f7dd120dc7813bf0e0e8a
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4020
|
Bug: [REFACTOR] : Setup payment_method_status from trackers to show in payment repsonse
### Feature Description
`payment_method` object from DB will be derived in `get_tracker` .
We need to set the `payment_method_status` depending upon the derived status for the payments with no `on_session`.
### Possible Implementation
`payment_method` object from DB will be derived in `get_tracker` we just need to set that up in `post_update_tracker`
### 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.rs b/crates/router/src/core/payments.rs
index b8a4c5dfc67..7f500eeee21 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -2210,7 +2210,6 @@ where
pub authorizations: Vec<diesel_models::authorization::Authorization>,
pub authentication: Option<(storage::Authentication, AuthenticationData)>,
pub frm_metadata: Option<serde_json::Value>,
- pub payment_method_status: Option<common_enums::PaymentMethodStatus>,
}
#[derive(Debug, Default, Clone)]
diff --git a/crates/router/src/core/payments/operations/payment_approve.rs b/crates/router/src/core/payments/operations/payment_approve.rs
index ba270e1d001..65b856364cc 100644
--- a/crates/router/src/core/payments/operations/payment_approve.rs
+++ b/crates/router/src/core/payments/operations/payment_approve.rs
@@ -165,7 +165,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
sessions_token: vec![],
card_cvc: None,
creds_identifier: None,
- payment_method_status: None,
pm_token: None,
connector_customer_id: None,
recurring_mandate_payment_data: None,
diff --git a/crates/router/src/core/payments/operations/payment_cancel.rs b/crates/router/src/core/payments/operations/payment_cancel.rs
index 8072984e20e..b25c0e2b909 100644
--- a/crates/router/src/core/payments/operations/payment_cancel.rs
+++ b/crates/router/src/core/payments/operations/payment_cancel.rs
@@ -175,7 +175,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
card_cvc: None,
creds_identifier,
pm_token: None,
- payment_method_status: None,
connector_customer_id: None,
recurring_mandate_payment_data: None,
ephemeral_key: None,
diff --git a/crates/router/src/core/payments/operations/payment_capture.rs b/crates/router/src/core/payments/operations/payment_capture.rs
index 9e6751757a1..47d339f15be 100644
--- a/crates/router/src/core/payments/operations/payment_capture.rs
+++ b/crates/router/src/core/payments/operations/payment_capture.rs
@@ -218,7 +218,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
sessions_token: vec![],
card_cvc: None,
creds_identifier,
- payment_method_status: None,
pm_token: None,
connector_customer_id: None,
recurring_mandate_payment_data: None,
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 0f08d14e439..8a773904ea3 100644
--- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs
+++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs
@@ -285,7 +285,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
multiple_capture_data: None,
redirect_response,
surcharge_details: None,
- payment_method_status: None,
frm_message: None,
payment_link_data: None,
incremental_authorization_details: None,
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index 3ecb98a9c9f..97b1d8e9817 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -609,7 +609,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
card_cvc: request.card_cvc.clone(),
creds_identifier,
pm_token: None,
- payment_method_status: None,
connector_customer_id: None,
recurring_mandate_payment_data,
ephemeral_key: None,
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index 6e185ea66d8..71f62b1cb79 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -410,7 +410,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
connector_customer_id: None,
recurring_mandate_payment_data,
ephemeral_key,
- payment_method_status: None,
multiple_capture_data: None,
redirect_response: None,
surcharge_details,
diff --git a/crates/router/src/core/payments/operations/payment_reject.rs b/crates/router/src/core/payments/operations/payment_reject.rs
index b59e87b826c..591ecb0a118 100644
--- a/crates/router/src/core/payments/operations/payment_reject.rs
+++ b/crates/router/src/core/payments/operations/payment_reject.rs
@@ -170,7 +170,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
surcharge_details: None,
frm_message: frm_response.ok(),
payment_link_data: None,
- payment_method_status: None,
incremental_authorization_details: None,
authorizations: vec![],
authentication: None,
diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs
index 447ca14b156..2afac8b6139 100644
--- a/crates/router/src/core/payments/operations/payment_response.rs
+++ b/crates/router/src/core/payments/operations/payment_response.rs
@@ -441,7 +441,12 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
router_data: types::RouterData<F, T, types::PaymentsResponseData>,
storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<PaymentData<F>> {
- payment_data.payment_method_status = router_data.payment_method_status;
+ router_data.payment_method_status.and_then(|status| {
+ payment_data
+ .payment_method_info
+ .as_mut()
+ .map(|info| info.status = status)
+ });
let (capture_update, mut payment_attempt_update) = match router_data.response.clone() {
Err(err) => {
let (capture_update, attempt_update) = match payment_data.multiple_capture_data {
@@ -888,7 +893,12 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
)?;
payment_data.payment_intent = payment_intent;
- payment_data.payment_method_status = router_data.payment_method_status;
+ router_data.payment_method_status.and_then(|status| {
+ payment_data
+ .payment_method_info
+ .as_mut()
+ .map(|info| info.status = status)
+ });
Ok(payment_data)
}
@@ -907,7 +917,10 @@ async fn update_payment_method_status<F: Clone>(
if pm.status != attempt_status.into() {
let updated_pm_status = common_enums::PaymentMethodStatus::from(attempt_status);
- payment_data.payment_method_status = Some(updated_pm_status);
+ payment_data
+ .payment_method_info
+ .as_mut()
+ .map(|info| info.status = updated_pm_status);
let pm_update = storage::PaymentMethodUpdate::StatusUpdate {
status: Some(updated_pm_status),
};
diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs
index 7129645601c..805b5fb3630 100644
--- a/crates/router/src/core/payments/operations/payment_session.rs
+++ b/crates/router/src/core/payments/operations/payment_session.rs
@@ -186,7 +186,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
sessions_token: vec![],
card_cvc: None,
creds_identifier,
- payment_method_status: None,
pm_token: None,
connector_customer_id: None,
recurring_mandate_payment_data: None,
diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rs
index ee85ffa8a5d..520336be0e1 100644
--- a/crates/router/src/core/payments/operations/payment_start.rs
+++ b/crates/router/src/core/payments/operations/payment_start.rs
@@ -181,7 +181,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
redirect_response: None,
surcharge_details: None,
frm_message: None,
- payment_method_status: None,
payment_link_data: None,
incremental_authorization_details: None,
authorizations: vec![],
diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs
index 60b2c807766..fd28fbd18d5 100644
--- a/crates/router/src/core/payments/operations/payment_status.rs
+++ b/crates/router/src/core/payments/operations/payment_status.rs
@@ -467,7 +467,6 @@ async fn get_tracker_for_sync<
card_cvc: None,
creds_identifier,
pm_token: None,
- payment_method_status: None,
connector_customer_id: None,
recurring_mandate_payment_data: None,
ephemeral_key: None,
diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs
index 626b123a835..2a0b99bc54b 100644
--- a/crates/router/src/core/payments/operations/payment_update.rs
+++ b/crates/router/src/core/payments/operations/payment_update.rs
@@ -421,7 +421,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
redirect_response: None,
surcharge_details,
frm_message: None,
- payment_method_status: None,
payment_link_data: None,
incremental_authorization_details: None,
authorizations: vec![],
diff --git a/crates/router/src/core/payments/operations/payments_incremental_authorization.rs b/crates/router/src/core/payments/operations/payments_incremental_authorization.rs
index d60e56de662..ab7ab56d94f 100644
--- a/crates/router/src/core/payments/operations/payments_incremental_authorization.rs
+++ b/crates/router/src/core/payments/operations/payments_incremental_authorization.rs
@@ -134,7 +134,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
sessions_token: vec![],
card_cvc: None,
creds_identifier: None,
- payment_method_status: None,
pm_token: None,
connector_customer_id: None,
recurring_mandate_payment_data: None,
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index 315ddd3b39b..b128c11baff 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -148,7 +148,7 @@ where
access_token: None,
session_token: None,
reference_id: None,
- payment_method_status: payment_data.payment_method_status,
+ payment_method_status: payment_data.payment_method_info.map(|info| info.status),
payment_method_token: payment_data.pm_token.map(types::PaymentMethodToken::Token),
connector_customer: payment_data.connector_customer_id,
recurring_mandate_payment_data: payment_data.recurring_mandate_payment_data,
@@ -778,7 +778,9 @@ where
payment_attempt.external_three_ds_authentication_attempted,
)
.set_payment_method_id(payment_attempt.payment_method_id)
- .set_payment_method_status(payment_data.payment_method_status)
+ .set_payment_method_status(
+ payment_data.payment_method_info.map(|info| info.status),
+ )
.to_owned(),
headers,
))
|
2024-03-13T07:52:01Z
|
## 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 -->
`payment_method` object from DB will be derived in `get_tracker` .
We need to set the `payment_method_status` depending upon the derived status for the payments with no `on_session`.
Moreover removing field `payment_method_status` from `PaymentsData` as it is already present in `payment_method_info`
### 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)?
-->
Sample curl:
### `Payment Create` with confirm as false:
```
curl --location 'http://127.0.0.1:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_eZdRVkfE8sbYE7JSzm2Tu0HAca0PHRY6u3JoSFBukHuxoYeXw7bgwr7Gy2DJn1kS' \
--data-raw '{
"amount": 6540,
"currency": "USD",
"confirm": false,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"amount_to_capture": 6540,
"customer_id": "cus_v6LovN3Zs9k8QQ2UYcbi",
"business_country": "US",
"business_label": "default",
"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": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4111111111111111",
"card_exp_month": "10",
"card_exp_year": "40",
"card_holder_name": "John",
"card_cvc": "737"
}
},
"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"
}
},
"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"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}
'
```
`Payment's Confirm` using token
```
curl --location 'http://127.0.0.1:8080/payments/pay_y5QhUc1Z5Y14FYOQ7qcm/confirm' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_xxxx' \
--data '{
"payment_token": "token_UCstChJwCzgeWKlPJijf",
"card_cvc": "123"
}'
```
Response should include these two fields
```
"payment_method_id": "pm_pzFcNslye3gZLxUlmDbg",
"payment_method_status": "active" (previously it was null)
```
The possible status and mappings are as follows:
```
AttemptStatus::Charged | AttemptStatus::Authorized => Self::Active,
AttemptStatus::Failure => Self::Inactive,
AttemptStatus::Voided
| AttemptStatus::Started
| AttemptStatus::Pending
| AttemptStatus::Unresolved
| AttemptStatus::CodInitiated
| AttemptStatus::Authorizing
| AttemptStatus::VoidInitiated
| AttemptStatus::AuthorizationFailed
| AttemptStatus::RouterDeclined
| AttemptStatus::AuthenticationSuccessful
| AttemptStatus::PaymentMethodAwaited
| AttemptStatus::AuthenticationFailed
| AttemptStatus::AuthenticationPending
| AttemptStatus::CaptureInitiated
| AttemptStatus::CaptureFailed
| AttemptStatus::VoidFailed
| AttemptStatus::AutoRefunded
| AttemptStatus::PartialCharged
| AttemptStatus::PartialChargedAndChargeable
| AttemptStatus::ConfirmationAwaited
| AttemptStatus::DeviceDataCollectionPending => Self::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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
9878fd90660fb14512e7f26f81b70fc4a1f58aa8
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4021
|
Bug: [BUG] : error message is different when invalid data is passed for `payment_method_data`
### Bug Description
It bugs out when invlaid card data is passed to the `payment_method_data`.
The following payment method data contains invalid card number
```json
{
"payment_method_data": {
"card": {
"card_number": "1234",
"card_exp_month": "10",
"card_exp_year": "12",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
}
}
```
### Expected Behavior
The returned error should be
```json
{
"error": "Json deserialize error: not a valid credit card number at line 26 column 33"
}
```
### Actual Behavior
The error displayed is
```json
{
"error": "Json deserialize error: data did not match any variant of untagged enum __Inner at line 32 column 5"
}
```
### Steps To Reproduce
Provide an unambiguous set of steps to reproduce this bug. Include code or configuration to reproduce, if relevant.
- Create a payment with below details
```bash
curl --location 'https://sandbox.hyperswitch.io/payments' \
--header 'Content-Type: application/json' \
--header 'api-key: dev_Nb5N9Vl2KPrbKqADO1F0olvVJanZMy0gWss6NaKXk5wfC5okqOWLvQN4W7i6e8XF' \
--data-raw '{
"amount": 6969,
"currency": "USD",
"confirm": false,
"name": "John Dough",
"capture_method": "manual",
"amount_to_capture": 6000,
"phone": "999999999",
"phone_country_code": "+65",
"customer_id": "cus_PAxm0MeCGM5TowgDKPc9",
"email": "example@juspay.in",
"setup_future_usage": "on_session",
"description": "Its my fourth payment request",
"authentication_type": "no_three_ds",
"routing": {
"type": "single",
"data": {
"connector": "stripe"
}
},
"payment_method_data": {
"card": {
"card_number": "1234",
"card_exp_month": "10",
"card_exp_year": "12",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
"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"
}
},
"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": "hola",
"statement_descriptor_suffix": "JS"
}'
```
### Context For The Bug
_No response_
### Environment
Are you using hyperswitch hosted version? No
### 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/payments.rs b/crates/api_models/src/payments.rs
index e5882fcb49d..dee5f2d0757 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -1095,12 +1095,19 @@ mod payment_method_data_serde {
#[serde(untagged)]
enum __Inner {
RewardString(String),
- OptionalPaymentMethod(Box<PaymentMethodDataRequest>),
+ OptionalPaymentMethod(serde_json::Value),
}
let deserialize_to_inner = __Inner::deserialize(deserializer)?;
match deserialize_to_inner {
- __Inner::OptionalPaymentMethod(value) => Ok(Some(*value)),
+ __Inner::OptionalPaymentMethod(value) => {
+ let parsed_value = serde_json::from_value::<PaymentMethodDataRequest>(value)
+ .map_err(|serde_json_error| {
+ serde::de::Error::custom(serde_json_error.to_string())
+ })?;
+
+ Ok(Some(parsed_value))
+ }
__Inner::RewardString(inner_string) => {
let payment_method_data = match inner_string.as_str() {
"reward" => PaymentMethodData::Reward,
@@ -4048,3 +4055,73 @@ pub enum PaymentLinkStatusWrap {
PaymentLinkStatus(PaymentLinkStatus),
IntentStatus(api_enums::IntentStatus),
}
+
+#[cfg(test)]
+mod payments_request_api_contract {
+ #![allow(clippy::unwrap_used)]
+ #![allow(clippy::panic)]
+ use std::str::FromStr;
+
+ use super::*;
+
+ #[test]
+ fn test_successful_card_deser() {
+ let payments_request = r#"
+ {
+ "amount": 6540,
+ "currency": "USD",
+ "payment_method": "card",
+ "payment_method_data": {
+ "card": {
+ "card_number": "4242424242424242",
+ "card_exp_month": "10",
+ "card_exp_year": "25",
+ "card_holder_name": "joseph Doe",
+ "card_cvc": "123"
+ }
+ }
+ }
+ "#;
+
+ let expected_card_number_string = "4242424242424242";
+ let expected_card_number = CardNumber::from_str(expected_card_number_string).unwrap();
+
+ let payments_request = serde_json::from_str::<PaymentsRequest>(payments_request);
+ assert!(payments_request.is_ok());
+
+ if let PaymentMethodData::Card(card_data) = payments_request
+ .unwrap()
+ .payment_method_data
+ .unwrap()
+ .payment_method_data
+ {
+ assert_eq!(card_data.card_number, expected_card_number);
+ } else {
+ panic!("Received unexpected response")
+ }
+ }
+
+ #[test]
+ fn test_successful_payment_method_reward() {
+ let payments_request = r#"
+ {
+ "amount": 6540,
+ "currency": "USD",
+ "payment_method": "reward",
+ "payment_method_data": "reward",
+ "payment_method_type": "evoucher"
+ }
+ "#;
+
+ let payments_request = serde_json::from_str::<PaymentsRequest>(payments_request);
+ assert!(payments_request.is_ok());
+ assert_eq!(
+ payments_request
+ .unwrap()
+ .payment_method_data
+ .unwrap()
+ .payment_method_data,
+ PaymentMethodData::Reward
+ );
+ }
+}
diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card CVC/.event.meta.json
similarity index 100%
rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method/.event.meta.json
rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card CVC/.event.meta.json
diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card CVC/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card CVC/event.test.js
new file mode 100644
index 00000000000..f1c2c6af775
--- /dev/null
+++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card CVC/event.test.js
@@ -0,0 +1,26 @@
+// Validate status 400
+pm.test("[POST]::/payments - Status code is 400", function () {
+ pm.response.to.be.error
+});
+
+// Validate if response header has matching content-type
+pm.test("[POST]::/payments - 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]::/payments - Response has JSON Body", function () {
+ pm.response.to.have.jsonBody();
+});
+
+// Set response object as internal variable
+let jsonData = {};
+try {
+ jsonData = pm.response.json();
+} catch (e) { }
+
+pm.test("[POST]::/payments - Response has appropriate error message", function () {
+ pm.expect(jsonData.error.message).eql("Invalid card_cvc length");
+})
diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card CVC/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card CVC/request.json
new file mode 100644
index 00000000000..77b40a8ece1
--- /dev/null
+++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card CVC/request.json
@@ -0,0 +1,41 @@
+{
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw_json_formatted": {
+ "amount": 6540,
+ "currency": "USD",
+ "payment_method": "card",
+ "payment_method_data": {
+ "card": {
+ "card_number": "4242424242424242",
+ "card_exp_month": "10",
+ "card_exp_year": "25",
+ "card_holder_name": "joseph Doe",
+ "card_cvc": ""
+ }
+ }
+ }
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": ["{{baseUrl}}"],
+ "path": ["payments"]
+ },
+ "description": "Create a Payment to ensure api contract is intact"
+}
diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card Number/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card Number/.event.meta.json
new file mode 100644
index 00000000000..4ac527d834a
--- /dev/null
+++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card Number/.event.meta.json
@@ -0,0 +1,6 @@
+{
+ "eventOrder": [
+ "event.test.js",
+ "event.prerequest.js"
+ ]
+}
diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card Number/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card Number/event.test.js
new file mode 100644
index 00000000000..c645f670ebf
--- /dev/null
+++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card Number/event.test.js
@@ -0,0 +1,16 @@
+// Validate status 400
+pm.test("[POST]::/payments - Status code is 400", function () {
+ pm.response.to.be.error
+});
+
+// Validate if response header has matching content-type
+pm.test("[POST]::/payments - 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]::/payments - Response has JSON Body", function () {
+ pm.response.to.have.jsonBody();
+});
diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card Number/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card Number/request.json
new file mode 100644
index 00000000000..2cb146e30ab
--- /dev/null
+++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Card Number/request.json
@@ -0,0 +1,41 @@
+{
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw_json_formatted": {
+ "amount": 6540,
+ "currency": "USD",
+ "payment_method": "card",
+ "payment_method_data": {
+ "card": {
+ "card_number": "1234",
+ "card_exp_month": "10",
+ "card_exp_year": "25",
+ "card_holder_name": "joseph Doe",
+ "card_cvc": "123"
+ }
+ }
+ }
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": ["{{baseUrl}}"],
+ "path": ["payments"]
+ },
+ "description": "Create a Payment to ensure api contract is intact"
+}
diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry month/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry month/.event.meta.json
new file mode 100644
index 00000000000..4ac527d834a
--- /dev/null
+++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry month/.event.meta.json
@@ -0,0 +1,6 @@
+{
+ "eventOrder": [
+ "event.test.js",
+ "event.prerequest.js"
+ ]
+}
diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry month/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry month/event.test.js
new file mode 100644
index 00000000000..8b3d52a3c6f
--- /dev/null
+++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry month/event.test.js
@@ -0,0 +1,26 @@
+// Validate status 400
+pm.test("[POST]::/payments - Status code is 400", function () {
+ pm.response.to.be.error
+});
+
+// Validate if response header has matching content-type
+pm.test("[POST]::/payments - 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]::/payments - Response has JSON Body", function () {
+ pm.response.to.have.jsonBody();
+});
+
+// Set response object as internal variable
+let jsonData = {};
+try {
+ jsonData = pm.response.json();
+} catch (e) { }
+
+pm.test("[POST]::/payments - Response has appropriate error message", function () {
+ pm.expect(jsonData.error.message).eql("Invalid Expiry Month");
+})
diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry month/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry month/request.json
new file mode 100644
index 00000000000..2c3d0fe427c
--- /dev/null
+++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry month/request.json
@@ -0,0 +1,41 @@
+{
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw_json_formatted": {
+ "amount": 6540,
+ "currency": "USD",
+ "payment_method": "card",
+ "payment_method_data": {
+ "card": {
+ "card_number": "4242424242424242",
+ "card_exp_month": "13",
+ "card_exp_year": "69",
+ "card_holder_name": "joseph Doe",
+ "card_cvc": "123"
+ }
+ }
+ }
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": ["{{baseUrl}}"],
+ "path": ["payments"]
+ },
+ "description": "Create a Payment to ensure api contract is intact"
+}
diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry year/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry year/.event.meta.json
new file mode 100644
index 00000000000..4ac527d834a
--- /dev/null
+++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry year/.event.meta.json
@@ -0,0 +1,6 @@
+{
+ "eventOrder": [
+ "event.test.js",
+ "event.prerequest.js"
+ ]
+}
diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry year/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry year/event.test.js
new file mode 100644
index 00000000000..cd3df41663f
--- /dev/null
+++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry year/event.test.js
@@ -0,0 +1,31 @@
+// Validate status 400
+pm.test("[POST]::/payments - Status code is 400", function () {
+ pm.response.to.be.error
+});
+
+// Validate if response header has matching content-type
+pm.test("[POST]::/payments - 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]::/payments - Response has JSON Body", function () {
+ pm.response.to.have.jsonBody();
+});
+
+// Set response object as internal variable
+let jsonData = {};
+try {
+ jsonData = pm.response.json();
+} catch (e) { }
+
+if (jsonData?.error?.message) {
+ pm.test(
+ "[POST]::/payments - Content check for error message to equal `Invalid Expiry Year`",
+ function () {
+ pm.expect(jsonData.error.message).to.eql("Invalid Expiry Year");
+ },
+ );
+}
diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry year/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry year/request.json
new file mode 100644
index 00000000000..63eda0afbe0
--- /dev/null
+++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Invalid Expiry year/request.json
@@ -0,0 +1,41 @@
+{
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw_json_formatted": {
+ "amount": 6540,
+ "currency": "USD",
+ "payment_method": "card",
+ "payment_method_data": {
+ "card": {
+ "card_number": "4242424242424242",
+ "card_exp_month": "10",
+ "card_exp_year": "22",
+ "card_holder_name": "joseph Doe",
+ "card_cvc": "123"
+ }
+ }
+ }
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": ["{{baseUrl}}"],
+ "path": ["payments"]
+ },
+ "description": "Create a Payment to ensure api contract is intact"
+}
diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Success/.event.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Success/.event.meta.json
new file mode 100644
index 00000000000..4ac527d834a
--- /dev/null
+++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Success/.event.meta.json
@@ -0,0 +1,6 @@
+{
+ "eventOrder": [
+ "event.test.js",
+ "event.prerequest.js"
+ ]
+}
diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Success/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Success/event.test.js
new file mode 100644
index 00000000000..600ad2ed90b
--- /dev/null
+++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Success/event.test.js
@@ -0,0 +1,33 @@
+// Validate status 2xx
+pm.test("[POST]::/payments - Status code is 2xx", function () {
+ pm.response.to.be.success;
+});
+
+// Validate if response header has matching content-type
+pm.test("[POST]::/payments - 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]::/payments - Response has JSON Body", function () {
+ pm.response.to.have.jsonBody();
+});
+
+
+// Set response object as internal variable
+let jsonData = {};
+try {
+ jsonData = pm.response.json();
+} catch (e) { }
+
+// Response body should have value "requires_payment_method" for "status"
+if (jsonData?.status) {
+ pm.test(
+ "[POST]::/payments - Content check if value for 'status' matches 'requires_confirmation'",
+ function () {
+ pm.expect(jsonData.status).to.eql("requires_confirmation");
+ },
+ );
+}
diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Success/request.json
similarity index 100%
rename from postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method/request.json
rename to postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method Success/request.json
diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method/event.test.js
deleted file mode 100644
index d462b381cc6..00000000000
--- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Card Payment Method/event.test.js
+++ /dev/null
@@ -1,9 +0,0 @@
-// Validate status 2xx
-pm.test("[POST]::/payments - Status code is 2xx", function () {
- pm.response.to.be.success;
-});
-
-// Validate if response has JSON Body
-pm.test("[POST]::/payments - Response has JSON Body", function () {
- pm.response.to.have.jsonBody();
-});
\ No newline at end of file
diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Reward Payment Method/event.test.js b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Reward Payment Method/event.test.js
index 0444324000a..c899ee4eb06 100644
--- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Reward Payment Method/event.test.js
+++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Reward Payment Method/event.test.js
@@ -19,53 +19,14 @@ pm.test("[POST]::/payments - Response has JSON Body", function () {
let jsonData = {};
try {
jsonData = pm.response.json();
-} catch (e) {}
-
-// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id
-if (jsonData?.payment_id) {
- pm.collectionVariables.set("payment_id", jsonData.payment_id);
- console.log(
- "- use {{payment_id}} as collection variable for value",
- jsonData.payment_id,
- );
-} else {
- console.log(
- "INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.",
- );
-}
-
-// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id
-if (jsonData?.mandate_id) {
- pm.collectionVariables.set("mandate_id", jsonData.mandate_id);
- console.log(
- "- use {{mandate_id}} as collection variable for value",
- jsonData.mandate_id,
- );
-} else {
- console.log(
- "INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.",
- );
-}
-
-// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret
-if (jsonData?.client_secret) {
- pm.collectionVariables.set("client_secret", jsonData.client_secret);
- console.log(
- "- use {{client_secret}} as collection variable for value",
- jsonData.client_secret,
- );
-} else {
- console.log(
- "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.",
- );
-}
+} catch (e) { }
// Response body should have value "requires_payment_method" for "status"
if (jsonData?.status) {
pm.test(
- "[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'",
+ "[POST]::/payments - Content check if value for 'status' matches 'requires_confirmation'",
function () {
- pm.expect(jsonData.status).to.eql("requires_payment_method");
+ pm.expect(jsonData.status).to.eql("requires_confirmation");
},
);
}
diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Reward Payment Method/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Reward Payment Method/request.json
index e5797a68e1b..52c5f911094 100644
--- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Reward Payment Method/request.json
+++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario32-Ensure API Contract for Payment Method Data/Payments - Reward Payment Method/request.json
@@ -19,7 +19,10 @@
},
"raw_json_formatted": {
"amount": 6540,
- "currency": "USD"
+ "currency": "USD",
+ "payment_method": "reward",
+ "payment_method_type": "evoucher",
+ "payment_method_data": "reward"
}
},
"url": {
diff --git a/postman/collection-json/stripe.postman_collection.json b/postman/collection-json/stripe.postman_collection.json
index 497d1c3669d..c3d6371fd7d 100644
--- a/postman/collection-json/stripe.postman_collection.json
+++ b/postman/collection-json/stripe.postman_collection.json
@@ -21800,21 +21800,39 @@
"name": "Scenario32-Ensure API Contract for Payment Method Data",
"item": [
{
- "name": "Payments - Card Payment Method",
+ "name": "Payments - Card Payment Method Invalid Card CVC",
"event": [
{
"listen": "test",
"script": {
"exec": [
- "// Validate status 2xx",
- "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
+ "// Validate status 400",
+ "pm.test(\"[POST]::/payments - Status code is 400\", function () {",
+ " pm.response.to.be.error",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - 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]::/payments - Response has JSON Body\", function () {",
" pm.response.to.have.jsonBody();",
- "});"
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) { }",
+ "",
+ "pm.test(\"[POST]::/payments - Response has appropriate error message\", function () {",
+ " pm.expect(jsonData.error.message).eql(\"Invalid card_cvc length\");",
+ "})",
+ ""
],
"type": "text/javascript"
}
@@ -21839,7 +21857,7 @@
"language": "json"
}
},
- "raw": "{\"amount\":6540,\"currency\":\"USD\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}}}"
+ "raw": "{\"amount\":6540,\"currency\":\"USD\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"\"}}}"
},
"url": {
"raw": "{{baseUrl}}/payments",
@@ -21854,15 +21872,77 @@
}
},
{
- "name": "Payments - Reward Payment Method",
+ "name": "Payments - Card Payment Method Invalid Card Number",
"event": [
{
"listen": "test",
"script": {
"exec": [
- "// Validate status 2xx",
- "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
+ "// Validate status 400",
+ "pm.test(\"[POST]::/payments - Status code is 400\", function () {",
+ " pm.response.to.be.error",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - 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]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":6540,\"currency\":\"USD\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"1234\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "Create a Payment to ensure api contract is intact"
+ }
+ },
+ {
+ "name": "Payments - Card Payment Method Invalid Expiry month",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 400",
+ "pm.test(\"[POST]::/payments - Status code is 400\", function () {",
+ " pm.response.to.be.error",
"});",
"",
"// Validate if response header has matching content-type",
@@ -21881,53 +21961,242 @@
"let jsonData = {};",
"try {",
" jsonData = pm.response.json();",
- "} catch (e) {}",
+ "} catch (e) { }",
"",
- "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
- "if (jsonData?.payment_id) {",
- " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
- " console.log(",
- " \"- use {{payment_id}} as collection variable for value\",",
- " jsonData.payment_id,",
+ "pm.test(\"[POST]::/payments - Response has appropriate error message\", function () {",
+ " pm.expect(jsonData.error.message).eql(\"Invalid Expiry Month\");",
+ "})",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":6540,\"currency\":\"USD\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"13\",\"card_exp_year\":\"69\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "Create a Payment to ensure api contract is intact"
+ }
+ },
+ {
+ "name": "Payments - Card Payment Method Invalid Expiry year",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 400",
+ "pm.test(\"[POST]::/payments - Status code is 400\", function () {",
+ " pm.response.to.be.error",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
" );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) { }",
+ "",
+ "if (jsonData?.error?.message) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check for error message to equal `Invalid Expiry Year`\",",
+ " function () {",
+ " pm.expect(jsonData.error.message).to.eql(\"Invalid Expiry Year\");",
+ " },",
" );",
"}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":6540,\"currency\":\"USD\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"22\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "Create a Payment to ensure api contract is intact"
+ }
+ },
+ {
+ "name": "Payments - Card Payment Method Success",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
"",
- "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
- "if (jsonData?.mandate_id) {",
- " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
- " console.log(",
- " \"- use {{mandate_id}} as collection variable for value\",",
- " jsonData.mandate_id,",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
" );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) { }",
+ "",
+ "// Response body should have value \"requires_payment_method\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'requires_confirmation'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"requires_confirmation\");",
+ " },",
" );",
"}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":6540,\"currency\":\"USD\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "Create a Payment to ensure api contract is intact"
+ }
+ },
+ {
+ "name": "Payments - Reward Payment Method",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
"",
- "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
- "if (jsonData?.client_secret) {",
- " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
- " console.log(",
- " \"- use {{client_secret}} as collection variable for value\",",
- " jsonData.client_secret,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - 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]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) { }",
"",
"// Response body should have value \"requires_payment_method\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'\",",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'requires_confirmation'\",",
" function () {",
- " pm.expect(jsonData.status).to.eql(\"requires_payment_method\");",
+ " pm.expect(jsonData.status).to.eql(\"requires_confirmation\");",
" },",
" );",
"}",
@@ -21956,7 +22225,7 @@
"language": "json"
}
},
- "raw": "{\"amount\":6540,\"currency\":\"USD\"}"
+ "raw": "{\"amount\":6540,\"currency\":\"USD\",\"payment_method\":\"reward\",\"payment_method_type\":\"evoucher\",\"payment_method_data\":\"reward\"}"
},
"url": {
"raw": "{{baseUrl}}/payments",
|
2024-03-08T12:24:17Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
## Description
<!-- Describe your changes in detail -->
If any invalid payment method data is passed, the error we received was wrong. This PR fixes it. More context can be found in the linked issue.
### 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)?
-->
- Postman and unit test 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
- [x] I added unit tests for my changes where possible
|
f5697f372c8e1f27c00f7dd120dc7813bf0e0e8a
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4017
|
Bug: [FEATURE] Add user roles for payouts
### Feature Description
Add respective variants and modules for managing permissions for payout operations.
PayoutRead,
PayoutWrite
Add these to user roles module.
### Possible Implementation
Add it similarly to existing roles.
### 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/api_models/src/user_role.rs b/crates/api_models/src/user_role.rs
index 2e3d60024d3..31da8386ab6 100644
--- a/crates/api_models/src/user_role.rs
+++ b/crates/api_models/src/user_role.rs
@@ -32,6 +32,8 @@ pub enum Permission {
UsersWrite,
MerchantAccountCreate,
WebhookEventRead,
+ PayoutWrite,
+ PayoutRead,
}
#[derive(Debug, serde::Serialize)]
@@ -48,6 +50,7 @@ pub enum PermissionModule {
ThreeDsDecisionManager,
SurchargeDecisionManager,
AccountCreate,
+ Payouts,
}
#[derive(Debug, serde::Serialize)]
diff --git a/crates/router/src/routes/payouts.rs b/crates/router/src/routes/payouts.rs
index c8d1c05bb37..0eeb0f27f07 100644
--- a/crates/router/src/routes/payouts.rs
+++ b/crates/router/src/routes/payouts.rs
@@ -9,7 +9,7 @@ use super::app::AppState;
use crate::types::api::payments as payment_types;
use crate::{
core::{api_locking, payouts::*},
- services::{api, authentication as auth},
+ services::{api, authentication as auth, authorization::permissions::Permission},
types::api::payouts as payout_types,
};
@@ -77,7 +77,11 @@ pub async fn payouts_retrieve(
&req,
payout_retrieve_request,
|state, auth, req| payouts_retrieve_core(state, auth.merchant_account, auth.key_store, req),
- &auth::ApiKeyAuth,
+ auth::auth_type(
+ &auth::ApiKeyAuth,
+ &auth::JWTAuth(Permission::PayoutRead),
+ req.headers(),
+ ),
api_locking::LockAction::NotApplicable,
))
.await
@@ -225,7 +229,11 @@ pub async fn payouts_list(
&req,
payload,
|state, auth, req| payouts_list_core(state, auth.merchant_account, req),
- &auth::ApiKeyAuth,
+ auth::auth_type(
+ &auth::ApiKeyAuth,
+ &auth::JWTAuth(Permission::PayoutRead),
+ req.headers(),
+ ),
api_locking::LockAction::NotApplicable,
))
.await
@@ -259,7 +267,11 @@ pub async fn payouts_list_by_filter(
&req,
payload,
|state, auth, req| payouts_filtered_list_core(state, auth.merchant_account, req),
- &auth::ApiKeyAuth,
+ auth::auth_type(
+ &auth::ApiKeyAuth,
+ &auth::JWTAuth(Permission::PayoutRead),
+ req.headers(),
+ ),
api_locking::LockAction::NotApplicable,
))
.await
@@ -293,7 +305,11 @@ pub async fn payouts_list_available_filters(
&req,
payload,
|state, auth, req| payouts_list_available_filters_core(state, auth.merchant_account, req),
- &auth::ApiKeyAuth,
+ auth::auth_type(
+ &auth::ApiKeyAuth,
+ &auth::JWTAuth(Permission::PayoutRead),
+ req.headers(),
+ ),
api_locking::LockAction::NotApplicable,
))
.await
diff --git a/crates/router/src/services/authorization/info.rs b/crates/router/src/services/authorization/info.rs
index 7b82e84d64c..371087cc303 100644
--- a/crates/router/src/services/authorization/info.rs
+++ b/crates/router/src/services/authorization/info.rs
@@ -41,6 +41,7 @@ pub enum PermissionModule {
ThreeDsDecisionManager,
SurchargeDecisionManager,
AccountCreate,
+ Payouts,
}
impl PermissionModule {
@@ -57,7 +58,8 @@ impl PermissionModule {
Self::Disputes => "Everything related to disputes - like creating and viewing dispute related information are within this module",
Self::ThreeDsDecisionManager => "View and configure 3DS decision rules configured for a merchant",
Self::SurchargeDecisionManager =>"View and configure surcharge decision rules configured for a merchant",
- Self::AccountCreate => "Create new account within your organization"
+ Self::AccountCreate => "Create new account within your organization",
+ Self::Payouts => "Everything related to payouts - like creating and viewing payout related information are within this module"
}
}
}
@@ -168,6 +170,14 @@ impl ModuleInfo {
Permission::MerchantAccountCreate,
]),
},
+ PermissionModule::Payouts => Self {
+ module: module_name,
+ description,
+ permissions: get_permission_info_from_permissions(&[
+ Permission::PayoutRead,
+ Permission::PayoutWrite,
+ ]),
+ },
}
}
}
@@ -184,10 +194,10 @@ fn get_group_info_from_permission_group(group: PermissionGroup) -> GroupInfo {
fn get_group_description(group: PermissionGroup) -> &'static str {
match group {
PermissionGroup::OperationsView => {
- "View Payments, Refunds, Mandates, Disputes and Customers"
+ "View Payments, Refunds, Payouts, Mandates, Disputes and Customers"
}
PermissionGroup::OperationsManage => {
- "Create, modify and delete Payments, Refunds, Mandates, Disputes and Customers"
+ "Create, modify and delete Payments, Refunds, Payouts, Mandates, Disputes and Customers"
}
PermissionGroup::ConnectorsView => {
"View connected Payment Processors, Payout Processors and Fraud & Risk Manager details"
diff --git a/crates/router/src/services/authorization/permission_groups.rs b/crates/router/src/services/authorization/permission_groups.rs
index 33647eb9a39..b68bef213cd 100644
--- a/crates/router/src/services/authorization/permission_groups.rs
+++ b/crates/router/src/services/authorization/permission_groups.rs
@@ -19,22 +19,24 @@ pub fn get_permissions_vec(permission_group: &PermissionGroup) -> &[Permission]
}
}
-pub static OPERATIONS_VIEW: [Permission; 6] = [
+pub static OPERATIONS_VIEW: [Permission; 7] = [
Permission::PaymentRead,
Permission::RefundRead,
Permission::MandateRead,
Permission::DisputeRead,
Permission::CustomerRead,
Permission::MerchantAccountRead,
+ Permission::PayoutRead,
];
-pub static OPERATIONS_MANAGE: [Permission; 6] = [
+pub static OPERATIONS_MANAGE: [Permission; 7] = [
Permission::PaymentWrite,
Permission::RefundWrite,
Permission::MandateWrite,
Permission::DisputeWrite,
Permission::CustomerWrite,
Permission::MerchantAccountRead,
+ Permission::PayoutWrite,
];
pub static CONNECTORS_VIEW: [Permission; 2] = [
diff --git a/crates/router/src/services/authorization/permissions.rs b/crates/router/src/services/authorization/permissions.rs
index b5ba72df05e..997eff8274e 100644
--- a/crates/router/src/services/authorization/permissions.rs
+++ b/crates/router/src/services/authorization/permissions.rs
@@ -31,6 +31,8 @@ pub enum Permission {
UsersWrite,
MerchantAccountCreate,
WebhookEventRead,
+ PayoutRead,
+ PayoutWrite,
}
impl Permission {
@@ -69,6 +71,8 @@ impl Permission {
Self::UsersWrite => "Invite users, assign and update roles",
Self::MerchantAccountCreate => "Create merchant account",
Self::WebhookEventRead => "View webhook events",
+ Self::PayoutRead => "View all payouts",
+ Self::PayoutWrite => "Create payout, download payout data",
}
}
}
diff --git a/crates/router/src/services/authorization/predefined_permissions.rs b/crates/router/src/services/authorization/predefined_permissions.rs
index bd0f37e2a0d..50f9a7196b8 100644
--- a/crates/router/src/services/authorization/predefined_permissions.rs
+++ b/crates/router/src/services/authorization/predefined_permissions.rs
@@ -64,6 +64,8 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy:
Permission::UsersRead,
Permission::UsersWrite,
Permission::MerchantAccountCreate,
+ Permission::PayoutRead,
+ Permission::PayoutWrite,
],
name: None,
is_invitable: false,
@@ -88,6 +90,7 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy:
Permission::MandateRead,
Permission::CustomerRead,
Permission::UsersRead,
+ Permission::PayoutRead,
],
name: None,
is_invitable: false,
@@ -126,6 +129,8 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy:
Permission::UsersRead,
Permission::UsersWrite,
Permission::MerchantAccountCreate,
+ Permission::PayoutRead,
+ Permission::PayoutWrite,
],
name: Some("Organization Admin"),
is_invitable: false,
@@ -164,6 +169,8 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy:
Permission::Analytics,
Permission::UsersRead,
Permission::UsersWrite,
+ Permission::PayoutRead,
+ Permission::PayoutWrite,
],
name: Some("Admin"),
is_invitable: true,
@@ -188,6 +195,7 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy:
Permission::CustomerRead,
Permission::Analytics,
Permission::UsersRead,
+ Permission::PayoutRead,
],
name: Some("View Only"),
is_invitable: true,
@@ -213,6 +221,7 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy:
Permission::Analytics,
Permission::UsersRead,
Permission::UsersWrite,
+ Permission::PayoutRead,
],
name: Some("IAM"),
is_invitable: true,
@@ -238,6 +247,7 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy:
Permission::CustomerRead,
Permission::Analytics,
Permission::UsersRead,
+ Permission::PayoutRead,
],
name: Some("Developer"),
is_invitable: true,
@@ -268,6 +278,8 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy:
Permission::CustomerRead,
Permission::Analytics,
Permission::UsersRead,
+ Permission::PayoutRead,
+ Permission::PayoutWrite,
],
name: Some("Operator"),
is_invitable: true,
@@ -289,6 +301,7 @@ pub static PREDEFINED_PERMISSIONS: Lazy<HashMap<&'static str, RoleInfo>> = Lazy:
Permission::MandateRead,
Permission::CustomerRead,
Permission::Analytics,
+ Permission::PayoutRead,
],
name: Some("Customer Support"),
is_invitable: true,
diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs
index 63272732e63..176b5810158 100644
--- a/crates/router/src/types/domain/user.rs
+++ b/crates/router/src/types/domain/user.rs
@@ -808,6 +808,7 @@ impl From<info::PermissionModule> for user_role_api::PermissionModule {
info::PermissionModule::ThreeDsDecisionManager => Self::ThreeDsDecisionManager,
info::PermissionModule::SurchargeDecisionManager => Self::SurchargeDecisionManager,
info::PermissionModule::AccountCreate => Self::AccountCreate,
+ info::PermissionModule::Payouts => Self::Payouts,
}
}
}
diff --git a/crates/router/src/utils/user_role.rs b/crates/router/src/utils/user_role.rs
index fa9eba8c27f..23b5bcf0f38 100644
--- a/crates/router/src/utils/user_role.rs
+++ b/crates/router/src/utils/user_role.rs
@@ -44,6 +44,8 @@ impl From<Permission> for user_role_api::Permission {
Permission::UsersWrite => Self::UsersWrite,
Permission::MerchantAccountCreate => Self::MerchantAccountCreate,
Permission::WebhookEventRead => Self::WebhookEventRead,
+ Permission::PayoutRead => Self::PayoutRead,
+ Permission::PayoutWrite => Self::PayoutWrite,
}
}
}
diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json
index 28b8f9ef796..1868eb9b4d9 100644
--- a/openapi/openapi_spec.json
+++ b/openapi/openapi_spec.json
@@ -3866,64 +3866,6 @@
]
}
},
- "/payouts/list": {
- "get": {
- "tags": [
- "Payouts"
- ],
- "summary": "Payouts - List",
- "description": "Payouts - List",
- "operationId": "List payouts",
- "responses": {
- "200": {
- "description": "Payouts listed",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/PayoutListResponse"
- }
- }
- }
- },
- "404": {
- "description": "Payout not found"
- }
- },
- "security": [
- {
- "api_key": []
- }
- ]
- },
- "post": {
- "tags": [
- "Payouts"
- ],
- "summary": "Payouts - Filter",
- "description": "Payouts - Filter",
- "operationId": "Filter payouts",
- "responses": {
- "200": {
- "description": "Payouts filtered",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/PayoutListResponse"
- }
- }
- }
- },
- "404": {
- "description": "Payout not found"
- }
- },
- "security": [
- {
- "api_key": []
- }
- ]
- }
- },
"/payouts/{payout_id}": {
"get": {
"tags": [
@@ -4116,6 +4058,64 @@
]
}
},
+ "/payouts/list": {
+ "get": {
+ "tags": [
+ "Payouts"
+ ],
+ "summary": "Payouts - List",
+ "description": "Payouts - List",
+ "operationId": "List payouts",
+ "responses": {
+ "200": {
+ "description": "Payouts listed",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/PayoutListResponse"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "Payout not found"
+ }
+ },
+ "security": [
+ {
+ "api_key": []
+ }
+ ]
+ },
+ "post": {
+ "tags": [
+ "Payouts"
+ ],
+ "summary": "Payouts - Filter",
+ "description": "Payouts - Filter",
+ "operationId": "Filter payouts",
+ "responses": {
+ "200": {
+ "description": "Payouts filtered",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/PayoutListResponse"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "Payout not found"
+ }
+ },
+ "security": [
+ {
+ "api_key": []
+ }
+ ]
+ }
+ },
"/api_keys/{merchant_id)": {
"post": {
"tags": [
|
2024-03-21T10:46:49Z
|
## 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 introduces user roles for `Payouts`. `PayoutRead` and `PayoutWrite` are added as permission under payout persmissions. This permission are added to list(get/post), retrieval and filter api's for payouts.
### 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).
-->
User permissions are used while user accessing the payout data via dashboard. `PayoutRead` and `PayoutWrite` are added as permission under payout persmissions. This permission are added to list(get/post), retrieval and filter api's of payouts.
## 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) User with `org_admin`, `internal_admin`, `merchant_admin`, `merchant_operator` will have PayoutRead and PayourWrite. All other user roles will have only `PayoutRead`. This below curl will get information of user role permissions.
```
curl --location --request GET '{{base_url}}/user/permission_info' \
--header 'Authorization: {{user_token}}' \
--header 'Content-Type: application/json' \
--data-raw '{
"email": "email@gmail.com"
}'
```
2) View all permissions from below curl
```
curl --location --request GET '{{base_url}}/user/role/list' \
--header 'Authorization: {{user_token}}'
```
Response :
```
[
{
"role_id": "merchant_view_only",
"permissions": [
"PayoutRead",
"CustomerRead",
"MerchantConnectorAccountRead",
"MandateRead",
"PaymentRead",
"SurchargeDecisionManagerRead",
"Analytics",
"DisputeRead",
"MerchantAccountRead",
"RoutingRead",
"UsersRead",
"RefundRead",
"ThreeDsDecisionManagerRead"
],
"role_name": "view_only",
"role_scope": "organization"
},
{
"role_id": "merchant_iam_admin",
"permissions": [
"UsersWrite",
"Analytics",
"UsersRead",
"PaymentRead",
"MerchantAccountRead",
"MandateRead",
"DisputeRead",
"PayoutRead",
"RefundRead",
"CustomerRead"
],
"role_name": "iam",
"role_scope": "organization"
},
{
"role_id": "merchant_developer",
"permissions": [
"RefundRead",
"PayoutRead",
"MerchantAccountWrite",
"ApiKeyWrite",
"PaymentRead",
"MerchantConnectorAccountRead",
"UsersRead",
"MandateRead",
"DisputeRead",
"MerchantAccountRead",
"CustomerRead",
"ApiKeyRead",
"Analytics",
"WebhookEventRead"
],
"role_name": "developer",
"role_scope": "organization"
},
{
"role_id": "merchant_customer_support",
"permissions": [
"MandateRead",
"PaymentRead",
"DisputeRead",
"PayoutRead",
"MerchantAccountRead",
"Analytics",
"RefundRead",
"CustomerRead",
"UsersRead"
],
"role_name": "customer_support",
"role_scope": "organization"
},
{
"role_id": "merchant_admin",
"permissions": [
"PayoutRead",
"MandateWrite",
"RoutingRead",
"PayoutWrite",
"RefundWrite",
"MerchantConnectorAccountWrite",
"SurchargeDecisionManagerRead",
"DisputeRead",
"RoutingWrite",
"SurchargeDecisionManagerWrite",
"Analytics",
"ThreeDsDecisionManagerWrite",
"MerchantAccountRead",
"UsersRead",
"MerchantConnectorAccountRead",
"UsersWrite",
"MandateRead",
"MerchantAccountWrite",
"ApiKeyRead",
"ApiKeyWrite",
"RefundRead",
"WebhookEventRead",
"PaymentWrite",
"PaymentRead",
"CustomerRead",
"DisputeWrite",
"ThreeDsDecisionManagerRead",
"CustomerWrite"
],
"role_name": "admin",
"role_scope": "organization"
},
{
"role_id": "merchant_operator",
"permissions": [
"RoutingRead",
"PayoutWrite",
"MerchantAccountRead",
"SurchargeDecisionManagerRead",
"PaymentWrite",
"CustomerWrite",
"MandateWrite",
"DisputeWrite",
"RefundWrite",
"DisputeRead",
"CustomerRead",
"MerchantConnectorAccountRead",
"ThreeDsDecisionManagerRead",
"UsersRead",
"PaymentRead",
"MandateRead",
"PayoutRead",
"RefundRead",
"Analytics"
],
"role_name": "operator",
"role_scope": "organization"
}
]
```
## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
5afd2c2a67f325960668f2b27c3519581f5877e1
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4033
|
Bug: [FEATURE] Integrate Plaid as an Open Banking Payment connector
### Feature Description
Integrate Plaid as an Open Banking Payment connector.
Pre-requisite would be the Open Banking payments core Integration - #3612
### Possible Implementation
Similar to regular connector integration
### 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/config/config.example.toml b/config/config.example.toml
index 2ffb69c3e3d..eab5e84df9c 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -206,6 +206,7 @@ payme.base_url = "https://sandbox.payme.io/"
paypal.base_url = "https://api-m.sandbox.paypal.com/"
payu.base_url = "https://secure.snd.payu.com/"
placetopay.base_url = "https://test.placetopay.com/rest/gateway"
+plaid.base_url = "https://sandbox.plaid.com"
powertranz.base_url = "https://staging.ptranz.com/api/"
prophetpay.base_url = "https://ccm-thirdparty.cps.golf/"
rapyd.base_url = "https://sandboxapi.rapyd.net"
diff --git a/config/development.toml b/config/development.toml
index 6d4914af8b4..827fd71e452 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -127,6 +127,7 @@ cards = [
"paypal",
"payu",
"placetopay",
+ "plaid",
"powertranz",
"prophetpay",
"shift4",
@@ -201,6 +202,7 @@ payme.base_url = "https://sandbox.payme.io/"
paypal.base_url = "https://api-m.sandbox.paypal.com/"
payu.base_url = "https://secure.snd.payu.com/"
placetopay.base_url = "https://test.placetopay.com/rest/gateway"
+plaid.base_url = "https://sandbox.plaid.com"
powertranz.base_url = "https://staging.ptranz.com/api/"
prophetpay.base_url = "https://ccm-thirdparty.cps.golf/"
rapyd.base_url = "https://sandboxapi.rapyd.net"
@@ -581,4 +583,7 @@ enabled = true
file_storage_backend = "file_system"
[unmasked_headers]
-keys = "user-agent"
\ No newline at end of file
+keys = "user-agent"
+
+[locker_open_banking_connectors]
+connector_list = []
\ No newline at end of file
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index 2f94d69790b..91f8480056e 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -140,6 +140,7 @@ payme.base_url = "https://sandbox.payme.io/"
paypal.base_url = "https://api-m.sandbox.paypal.com/"
payu.base_url = "https://secure.snd.payu.com/"
placetopay.base_url = "https://test.placetopay.com/rest/gateway"
+plaid.base_url = "https://sandbox.plaid.com"
powertranz.base_url = "https://staging.ptranz.com/api/"
prophetpay.base_url = "https://ccm-thirdparty.cps.golf/"
rapyd.base_url = "https://sandboxapi.rapyd.net"
@@ -206,6 +207,7 @@ cards = [
"paypal",
"payu",
"placetopay",
+ "plaid",
"powertranz",
"prophetpay",
"shift4",
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs
index bf88eca0a0e..067f69b56e1 100644
--- a/crates/api_models/src/admin.rs
+++ b/crates/api_models/src/admin.rs
@@ -479,6 +479,32 @@ pub struct MerchantConnectorCreate {
pub status: Option<api_enums::ConnectorStatus>,
}
+#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
+pub enum MerchantAccountData {
+ Iban {
+ iban: Secret<String>,
+ name: String,
+ },
+ Bacs {
+ account_number: Secret<String>,
+ sort_code: Secret<String>,
+ name: String,
+ },
+}
+
+#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
+pub enum MerchantRecipientData {
+ RecipientId(Secret<String>),
+ WalletId(Secret<String>),
+ AccountData(MerchantAccountData),
+}
+#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
+pub struct OpenBankingAuthType {
+ pub api_key: Secret<String>,
+ pub key1: Secret<String>,
+ pub merchant_data: MerchantRecipientData,
+}
+
// Different patterns of authentication.
#[derive(Default, Debug, Clone, serde::Deserialize, serde::Serialize)]
#[serde(tag = "auth_type")]
@@ -505,6 +531,11 @@ pub enum ConnectorAuthType {
CurrencyAuthKey {
auth_key_map: HashMap<common_enums::Currency, pii::SecretSerdeValue>,
},
+ OpenBankingAuth {
+ api_key: Secret<String>,
+ key1: Secret<String>,
+ merchant_data: MerchantRecipientData,
+ },
#[default]
NoKey,
}
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index dee5f2d0757..a21d03aba90 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -1346,6 +1346,7 @@ impl GetPaymentMethodType for BankRedirectData {
Self::OnlineBankingThailand { .. } => {
api_enums::PaymentMethodType::OnlineBankingThailand
}
+ Self::OpenBanking { .. } => api_enums::PaymentMethodType::OpenBanking,
}
}
}
@@ -1620,6 +1621,7 @@ pub enum BankRedirectData {
#[schema(value_type = BankNames)]
issuer: api_enums::BankNames,
},
+ OpenBanking {},
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)]
@@ -2263,7 +2265,9 @@ pub enum NextActionData {
bank_transfer_steps_and_charges_details: BankTransferNextStepsData,
},
/// Contains third party sdk session token response
- ThirdPartySdkSessionToken { session_token: Option<SessionToken> },
+ ThirdPartySdkSessionToken {
+ session_token: Option<SessionTokenType>,
+ },
/// Contains url for Qr code image, this qr code has to be shown in sdk
QrCodeInformation {
#[schema(value_type = String)]
@@ -3319,6 +3323,13 @@ pub struct SessionTokenForSimplifiedApplePay {
pub initiative_context: String,
}
+#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)]
+#[serde(untagged)]
+pub enum SessionTokenType {
+ Wallet(SessionToken),
+ OpenBanking(OpenBankingSessionToken),
+}
+
#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)]
#[serde(tag = "wallet_name")]
#[serde(rename_all = "snake_case")]
@@ -3390,6 +3401,13 @@ pub struct PaypalSessionTokenResponse {
pub session_token: String,
}
+#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)]
+#[serde(rename_all = "lowercase")]
+pub struct OpenBankingSessionToken {
+ /// The session token for OpenBanking Connectors
+ pub open_banking_session_token: String,
+}
+
#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)]
#[serde(rename_all = "lowercase")]
pub struct ApplepaySessionTokenResponse {
@@ -3523,7 +3541,7 @@ pub struct PaymentsSessionResponse {
#[schema(value_type = String)]
pub client_secret: Secret<String, pii::ClientSecret>,
/// The list of session token object
- pub session_token: Vec<SessionToken>,
+ pub session_token: Vec<SessionTokenType>,
}
#[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index 9cf138ed330..58c0152d8db 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -163,6 +163,7 @@ pub enum RoutableConnectors {
Worldline,
Worldpay,
Zen,
+ Plaid,
}
impl AttemptStatus {
@@ -1345,6 +1346,7 @@ pub enum PaymentMethodType {
FamilyMart,
Seicomart,
PayEasy,
+ OpenBanking,
}
/// Indicates the type of payment method. Eg: 'card', 'wallet', etc.
diff --git a/crates/common_enums/src/transformers.rs b/crates/common_enums/src/transformers.rs
index 63abfdb3f73..86ec6d3a709 100644
--- a/crates/common_enums/src/transformers.rs
+++ b/crates/common_enums/src/transformers.rs
@@ -1873,6 +1873,7 @@ impl From<PaymentMethodType> for PaymentMethod {
PaymentMethodType::FamilyMart => Self::Voucher,
PaymentMethodType::Seicomart => Self::Voucher,
PaymentMethodType::PayEasy => Self::Voucher,
+ PaymentMethodType::OpenBanking => Self::BankRedirect,
}
}
}
diff --git a/crates/euclid/src/frontend/dir/enums.rs b/crates/euclid/src/frontend/dir/enums.rs
index 0b71f916d03..982ae4a3c43 100644
--- a/crates/euclid/src/frontend/dir/enums.rs
+++ b/crates/euclid/src/frontend/dir/enums.rs
@@ -154,6 +154,7 @@ pub enum BankRedirectType {
OpenBankingUk,
Przelewy24,
Trustly,
+ OpenBanking,
}
#[derive(
Clone,
diff --git a/crates/euclid/src/frontend/dir/lowering.rs b/crates/euclid/src/frontend/dir/lowering.rs
index b1f03e8dd55..d09e0cf7f7c 100644
--- a/crates/euclid/src/frontend/dir/lowering.rs
+++ b/crates/euclid/src/frontend/dir/lowering.rs
@@ -159,6 +159,7 @@ impl From<enums::BankRedirectType> for global_enums::PaymentMethodType {
enums::BankRedirectType::OpenBankingUk => Self::OpenBankingUk,
enums::BankRedirectType::Przelewy24 => Self::Przelewy24,
enums::BankRedirectType::Trustly => Self::Trustly,
+ enums::BankRedirectType::OpenBanking => Self::OpenBanking,
}
}
}
diff --git a/crates/euclid/src/frontend/dir/transformers.rs b/crates/euclid/src/frontend/dir/transformers.rs
index c99b39e36f4..d2f1a752734 100644
--- a/crates/euclid/src/frontend/dir/transformers.rs
+++ b/crates/euclid/src/frontend/dir/transformers.rs
@@ -164,6 +164,9 @@ impl IntoDirValue for (global_enums::PaymentMethodType, global_enums::PaymentMet
global_enums::PaymentMethodType::CardRedirect => {
Ok(dirval!(CardRedirectType = CardRedirect))
}
+ global_enums::PaymentMethodType::OpenBanking => {
+ Ok(dirval!(BankRedirectType = OpenBanking))
+ }
}
}
}
diff --git a/crates/kgraph_utils/src/transformers.rs b/crates/kgraph_utils/src/transformers.rs
index 5bcb64fd875..00834f8b840 100644
--- a/crates/kgraph_utils/src/transformers.rs
+++ b/crates/kgraph_utils/src/transformers.rs
@@ -283,6 +283,9 @@ impl IntoDirValue for (api_enums::PaymentMethodType, api_enums::PaymentMethod) {
api_enums::PaymentMethodType::CardRedirect => {
Ok(dirval!(CardRedirectType = CardRedirect))
}
+ api_enums::PaymentMethodType::OpenBanking => {
+ Ok(dirval!(BankRedirectType = OpenBanking))
+ }
}
}
}
diff --git a/crates/pm_auth/src/connector/plaid.rs b/crates/pm_auth/src/connector/plaid.rs
index dfcfbb7eddc..1b8568a1e7e 100644
--- a/crates/pm_auth/src/connector/plaid.rs
+++ b/crates/pm_auth/src/connector/plaid.rs
@@ -15,7 +15,9 @@ use crate::{
types::{
self as auth_types,
api::{
- auth_service::{self, BankAccountCredentials, ExchangeToken, LinkToken},
+ auth_service::{
+ self, BankAccountCredentials, ExchangeToken, LinkToken, RecipientCreate,
+ },
ConnectorCommon, ConnectorCommonExt, ConnectorIntegration,
},
},
@@ -89,6 +91,8 @@ impl ConnectorCommon for Plaid {
}
impl auth_service::AuthService for Plaid {}
+impl auth_service::PaymentInitiationRecipientCreate for Plaid {}
+impl auth_service::PaymentInitiation for Plaid {}
impl auth_service::AuthServiceLinkToken for Plaid {}
impl ConnectorIntegration<LinkToken, auth_types::LinkTokenRequest, auth_types::LinkTokenResponse>
@@ -338,3 +342,89 @@ impl
self.build_error_response(res)
}
}
+
+impl
+ ConnectorIntegration<
+ RecipientCreate,
+ auth_types::RecipientCreateRequest,
+ auth_types::RecipientCreateResponse,
+ > for Plaid
+{
+ fn get_headers(
+ &self,
+ req: &auth_types::RecipientCreateRouterData,
+ connectors: &auth_types::PaymentMethodAuthConnectors,
+ ) -> errors::CustomResult<Vec<(String, 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: &auth_types::RecipientCreateRouterData,
+ connectors: &auth_types::PaymentMethodAuthConnectors,
+ ) -> errors::CustomResult<String, errors::ConnectorError> {
+ Ok(format!(
+ "{}{}",
+ self.base_url(connectors),
+ "/payment_initiation/recipient/create"
+ ))
+ }
+
+ fn get_request_body(
+ &self,
+ req: &auth_types::RecipientCreateRouterData,
+ ) -> errors::CustomResult<RequestContent, errors::ConnectorError> {
+ let req_obj = plaid::PlaidRecipientCreateRequest::try_from(req)?;
+ Ok(RequestContent::Json(Box::new(req_obj)))
+ }
+
+ fn build_request(
+ &self,
+ req: &auth_types::RecipientCreateRouterData,
+ connectors: &auth_types::PaymentMethodAuthConnectors,
+ ) -> errors::CustomResult<Option<Request>, errors::ConnectorError> {
+ Ok(Some(
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&auth_types::PaymentInitiationRecipientCreateType::get_url(
+ self, req, connectors,
+ )?)
+ .attach_default_headers()
+ .headers(
+ auth_types::PaymentInitiationRecipientCreateType::get_headers(
+ self, req, connectors,
+ )?,
+ )
+ .set_body(
+ auth_types::PaymentInitiationRecipientCreateType::get_request_body(self, req)?,
+ )
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &auth_types::RecipientCreateRouterData,
+ res: auth_types::Response,
+ ) -> errors::CustomResult<auth_types::RecipientCreateRouterData, errors::ConnectorError> {
+ let response: plaid::PlaidRecipientCreateResponse = res
+ .response
+ .parse_struct("PlaidRecipientCreateResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ <auth_types::RecipientCreateRouterData>::try_from(auth_types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+ fn get_error_response(
+ &self,
+ res: auth_types::Response,
+ ) -> errors::CustomResult<auth_types::ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res)
+ }
+}
diff --git a/crates/pm_auth/src/connector/plaid/transformers.rs b/crates/pm_auth/src/connector/plaid/transformers.rs
index 5e1ad67aead..c4e018663f4 100644
--- a/crates/pm_auth/src/connector/plaid/transformers.rs
+++ b/crates/pm_auth/src/connector/plaid/transformers.rs
@@ -112,6 +112,105 @@ impl TryFrom<&types::ExchangeTokenRouterData> for PlaidExchangeTokenRequest {
}
}
+#[derive(Debug, Serialize, Eq, PartialEq)]
+pub struct PlaidRecipientCreateRequest {
+ pub name: String,
+ #[serde(flatten)]
+ pub account_data: PlaidRecipientAccountData,
+ pub address: Option<PlaidRecipientCreateAddress>,
+}
+
+#[derive(Debug, Deserialize, Eq, PartialEq)]
+pub struct PlaidRecipientCreateResponse {
+ pub recipient_id: String,
+}
+
+#[derive(Debug, Serialize, Eq, PartialEq)]
+#[serde(rename_all = "lowercase")]
+pub enum PlaidRecipientAccountData {
+ Iban(Secret<String>),
+ Bacs {
+ sort_code: Secret<String>,
+ account: Secret<String>,
+ },
+}
+
+impl From<&types::RecipientAccountData> for PlaidRecipientAccountData {
+ fn from(item: &types::RecipientAccountData) -> Self {
+ match item {
+ types::RecipientAccountData::Iban(iban) => Self::Iban(iban.clone()),
+ types::RecipientAccountData::Bacs {
+ sort_code,
+ account_number,
+ } => Self::Bacs {
+ sort_code: sort_code.clone(),
+ account: account_number.clone(),
+ },
+ }
+ }
+}
+
+#[derive(Debug, Serialize, Eq, PartialEq)]
+pub struct PlaidRecipientCreateAddress {
+ pub street: String,
+ pub city: String,
+ pub postal_code: String,
+ pub country: String,
+}
+
+impl From<&types::RecipientCreateAddress> for PlaidRecipientCreateAddress {
+ fn from(item: &types::RecipientCreateAddress) -> Self {
+ Self {
+ street: item.street.clone(),
+ city: item.city.clone(),
+ postal_code: item.postal_code.clone(),
+ country: common_enums::CountryAlpha2::to_string(&item.country),
+ }
+ }
+}
+
+impl TryFrom<&types::RecipientCreateRouterData> for PlaidRecipientCreateRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(item: &types::RecipientCreateRouterData) -> Result<Self, Self::Error> {
+ Ok(Self {
+ name: item.request.name.clone(),
+ account_data: PlaidRecipientAccountData::from(&item.request.account_data),
+ address: item
+ .request
+ .address
+ .as_ref()
+ .map(PlaidRecipientCreateAddress::from),
+ })
+ }
+}
+
+impl<F, T>
+ TryFrom<
+ types::ResponseRouterData<
+ F,
+ PlaidRecipientCreateResponse,
+ T,
+ types::RecipientCreateResponse,
+ >,
+ > for types::PaymentAuthRouterData<F, T, types::RecipientCreateResponse>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: types::ResponseRouterData<
+ F,
+ PlaidRecipientCreateResponse,
+ T,
+ types::RecipientCreateResponse,
+ >,
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ response: Ok(types::RecipientCreateResponse {
+ recipient_id: item.response.recipient_id,
+ }),
+ ..item.data
+ })
+ }
+}
#[derive(Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub struct PlaidBankAccountCredentialsRequest {
@@ -269,6 +368,7 @@ impl<F, T>
pub struct PlaidAuthType {
pub client_id: Secret<String>,
pub secret: Secret<String>,
+ pub merchant_data: Option<types::MerchantRecipientData>,
}
impl TryFrom<&types::ConnectorAuthType> for PlaidAuthType {
@@ -278,6 +378,16 @@ impl TryFrom<&types::ConnectorAuthType> for PlaidAuthType {
types::ConnectorAuthType::BodyKey { client_id, secret } => Ok(Self {
client_id: client_id.to_owned(),
secret: secret.to_owned(),
+ merchant_data: None,
+ }),
+ types::ConnectorAuthType::OpenBankingAuth {
+ api_key,
+ key1,
+ merchant_data,
+ } => Ok(Self {
+ client_id: api_key.to_owned(),
+ secret: key1.to_owned(),
+ merchant_data: Some(merchant_data.clone()),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
diff --git a/crates/pm_auth/src/types.rs b/crates/pm_auth/src/types.rs
index 6f5875247f1..71e2f543c17 100644
--- a/crates/pm_auth/src/types.rs
+++ b/crates/pm_auth/src/types.rs
@@ -2,9 +2,10 @@ pub mod api;
use std::marker::PhantomData;
-use api::auth_service::{BankAccountCredentials, ExchangeToken, LinkToken};
-use common_enums::PaymentMethodType;
+use api::auth_service::{BankAccountCredentials, ExchangeToken, LinkToken, RecipientCreate};
+use common_enums::{CountryAlpha2, PaymentMethodType};
use masking::Secret;
+
#[derive(Debug, Clone)]
pub struct PaymentAuthRouterData<F, Request, Response> {
pub flow: PhantomData<F>,
@@ -85,6 +86,38 @@ pub type BankDetailsRouterData = PaymentAuthRouterData<
BankAccountCredentialsResponse,
>;
+#[derive(Debug, Clone)]
+pub struct RecipientCreateRequest {
+ pub name: String,
+ pub account_data: RecipientAccountData,
+ pub address: Option<RecipientCreateAddress>,
+}
+
+#[derive(Debug, Clone)]
+pub struct RecipientCreateResponse {
+ pub recipient_id: String,
+}
+
+#[derive(Debug, Clone)]
+pub enum RecipientAccountData {
+ Iban(Secret<String>),
+ Bacs {
+ sort_code: Secret<String>,
+ account_number: Secret<String>,
+ },
+}
+
+#[derive(Debug, Clone)]
+pub struct RecipientCreateAddress {
+ pub street: String,
+ pub city: String,
+ pub postal_code: String,
+ pub country: CountryAlpha2,
+}
+
+pub type RecipientCreateRouterData =
+ PaymentAuthRouterData<RecipientCreate, RecipientCreateRequest, RecipientCreateResponse>;
+
pub type PaymentAuthLinkTokenType =
dyn self::api::ConnectorIntegration<LinkToken, LinkTokenRequest, LinkTokenResponse>;
@@ -97,6 +130,12 @@ pub type PaymentAuthBankAccountDetailsType = dyn self::api::ConnectorIntegration
BankAccountCredentialsResponse,
>;
+pub type PaymentInitiationRecipientCreateType = dyn self::api::ConnectorIntegration<
+ RecipientCreate,
+ RecipientCreateRequest,
+ RecipientCreateResponse,
+>;
+
#[derive(Clone, Debug, strum::EnumString, strum::Display)]
#[strum(serialize_all = "snake_case")]
pub enum PaymentMethodAuthConnectors {
@@ -129,12 +168,38 @@ impl ErrorResponse {
}
}
+#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
+pub enum MerchantAccountData {
+ Iban {
+ iban: Secret<String>,
+ name: String,
+ },
+ Bacs {
+ account_number: Secret<String>,
+ sort_code: Secret<String>,
+ name: String,
+ },
+}
+
+#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum MerchantRecipientData {
+ RecipientId(Secret<String>),
+ WalletId(Secret<String>),
+ AccountData(MerchantAccountData),
+}
+
#[derive(Default, Debug, Clone, serde::Deserialize)]
pub enum ConnectorAuthType {
BodyKey {
client_id: Secret<String>,
secret: Secret<String>,
},
+ OpenBankingAuth {
+ api_key: Secret<String>,
+ key1: Secret<String>,
+ merchant_data: MerchantRecipientData,
+ },
#[default]
NoKey,
}
diff --git a/crates/pm_auth/src/types/api.rs b/crates/pm_auth/src/types/api.rs
index 3684e34ec05..d4edf160985 100644
--- a/crates/pm_auth/src/types/api.rs
+++ b/crates/pm_auth/src/types/api.rs
@@ -10,7 +10,10 @@ use masking::Maskable;
use crate::{
core::errors::ConnectorError,
- types::{self as auth_types, api::auth_service::AuthService},
+ types::{
+ self as auth_types,
+ api::auth_service::{AuthService, PaymentInitiation},
+ },
};
#[async_trait::async_trait]
@@ -125,9 +128,9 @@ where
}
}
-pub trait AuthServiceConnector: AuthService + Send + Debug {}
+pub trait AuthServiceConnector: AuthService + Send + Debug + PaymentInitiation {}
-impl<T: Send + Debug + AuthService> AuthServiceConnector for T {}
+impl<T: Send + Debug + AuthService + PaymentInitiation> AuthServiceConnector for T {}
pub type BoxedPaymentAuthConnector = Box<&'static (dyn AuthServiceConnector + Sync)>;
diff --git a/crates/pm_auth/src/types/api/auth_service.rs b/crates/pm_auth/src/types/api/auth_service.rs
index 35d44970d51..498b6bec40e 100644
--- a/crates/pm_auth/src/types/api/auth_service.rs
+++ b/crates/pm_auth/src/types/api/auth_service.rs
@@ -1,6 +1,7 @@
use crate::types::{
BankAccountCredentialsRequest, BankAccountCredentialsResponse, ExchangeTokenRequest,
- ExchangeTokenResponse, LinkTokenRequest, LinkTokenResponse,
+ ExchangeTokenResponse, LinkTokenRequest, LinkTokenResponse, RecipientCreateRequest,
+ RecipientCreateResponse,
};
pub trait AuthService:
@@ -11,6 +12,8 @@ pub trait AuthService:
{
}
+pub trait PaymentInitiation: super::ConnectorCommon + PaymentInitiationRecipientCreate {}
+
#[derive(Debug, Clone)]
pub struct LinkToken;
@@ -38,3 +41,11 @@ pub trait AuthServiceBankAccountCredentials:
>
{
}
+
+#[derive(Debug, Clone)]
+pub struct RecipientCreate;
+
+pub trait PaymentInitiationRecipientCreate:
+ super::ConnectorIntegration<RecipientCreate, RecipientCreateRequest, RecipientCreateResponse>
+{
+}
diff --git a/crates/router/src/compatibility/stripe/payment_intents/types.rs b/crates/router/src/compatibility/stripe/payment_intents/types.rs
index a74f16cee79..f76437ff97f 100644
--- a/crates/router/src/compatibility/stripe/payment_intents/types.rs
+++ b/crates/router/src/compatibility/stripe/payment_intents/types.rs
@@ -848,8 +848,18 @@ pub(crate) fn into_stripe_next_action(
bank_transfer_steps_and_charges_details,
},
payments::NextActionData::ThirdPartySdkSessionToken { session_token } => {
- StripeNextAction::ThirdPartySdkSessionToken { session_token }
+ match session_token {
+ Some(payments::SessionTokenType::Wallet(token)) => {
+ StripeNextAction::ThirdPartySdkSessionToken {
+ session_token: Some(token),
+ }
+ }
+ _ => StripeNextAction::ThirdPartySdkSessionToken {
+ session_token: None,
+ },
+ }
}
+
payments::NextActionData::QrCodeInformation {
image_data_url,
display_to_timestamp,
diff --git a/crates/router/src/compatibility/stripe/setup_intents/types.rs b/crates/router/src/compatibility/stripe/setup_intents/types.rs
index a05a8c241d0..51c83624763 100644
--- a/crates/router/src/compatibility/stripe/setup_intents/types.rs
+++ b/crates/router/src/compatibility/stripe/setup_intents/types.rs
@@ -421,7 +421,16 @@ pub(crate) fn into_stripe_next_action(
bank_transfer_steps_and_charges_details,
},
payments::NextActionData::ThirdPartySdkSessionToken { session_token } => {
- StripeNextAction::ThirdPartySdkSessionToken { session_token }
+ match session_token {
+ Some(payments::SessionTokenType::Wallet(token)) => {
+ StripeNextAction::ThirdPartySdkSessionToken {
+ session_token: Some(token),
+ }
+ }
+ _ => StripeNextAction::ThirdPartySdkSessionToken {
+ session_token: None,
+ },
+ }
}
payments::NextActionData::QrCodeInformation {
image_data_url,
diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rs
index f89d1811988..b2a67712ce9 100644
--- a/crates/router/src/configs/secrets_transformers.rs
+++ b/crates/router/src/configs/secrets_transformers.rs
@@ -361,5 +361,6 @@ pub(crate) async fn fetch_raw_secrets(
connector_onboarding,
cors: conf.cors,
unmasked_headers: conf.unmasked_headers,
+ locker_open_banking_connectors: conf.locker_open_banking_connectors,
}
}
diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs
index dc4826dfed6..89b5b81b1a4 100644
--- a/crates/router/src/configs/settings.rs
+++ b/crates/router/src/configs/settings.rs
@@ -116,6 +116,7 @@ pub struct Settings<S: SecretState> {
#[cfg(feature = "olap")]
pub connector_onboarding: SecretStateContainer<ConnectorOnboarding, S>,
pub unmasked_headers: UnmaskedHeaders,
+ pub locker_open_banking_connectors: LockerBasedRecipientConnectorList,
}
#[derive(Debug, Deserialize, Clone, Default)]
@@ -511,6 +512,7 @@ pub struct Connectors {
pub paypal: ConnectorParams,
pub payu: ConnectorParams,
pub placetopay: ConnectorParams,
+ pub plaid: ConnectorParams,
pub powertranz: ConnectorParams,
pub prophetpay: ConnectorParams,
pub rapyd: ConnectorParams,
@@ -624,6 +626,11 @@ pub struct ApplePayDecryptConifg {
pub apple_pay_merchant_cert_key: Secret<String>,
}
+#[derive(Debug, Deserialize, Clone, Default)]
+pub struct LockerBasedRecipientConnectorList {
+ pub connector_list: HashSet<String>,
+}
+
#[derive(Debug, Deserialize, Clone, Default)]
pub struct ConnectorRequestReferenceIdConfig {
pub merchant_ids_send_payment_id_as_connector_request_id: HashSet<String>,
diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs
index eccdf3f9ddf..cd829718652 100644
--- a/crates/router/src/connector.rs
+++ b/crates/router/src/connector.rs
@@ -37,6 +37,7 @@ pub mod payme;
pub mod paypal;
pub mod payu;
pub mod placetopay;
+pub mod plaid;
pub mod powertranz;
pub mod prophetpay;
pub mod rapyd;
@@ -67,8 +68,8 @@ pub use self::{
iatapay::Iatapay, klarna::Klarna, mollie::Mollie, multisafepay::Multisafepay,
nexinets::Nexinets, nmi::Nmi, noon::Noon, nuvei::Nuvei, opayo::Opayo, opennode::Opennode,
payeezy::Payeezy, payme::Payme, 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,
+ plaid::Plaid, 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/adyen.rs b/crates/router/src/connector/adyen.rs
index 67e319ddc22..ed1ea772898 100644
--- a/crates/router/src/connector/adyen.rs
+++ b/crates/router/src/connector/adyen.rs
@@ -210,6 +210,7 @@ impl ConnectorValidation for Adyen {
| PaymentMethodType::SamsungPay
| PaymentMethodType::Evoucher
| PaymentMethodType::Cashapp
+ | PaymentMethodType::OpenBanking
| PaymentMethodType::UpiCollect => {
capture_method_not_supported!(connector, capture_method, payment_method_type)
}
diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs
index c44d590e2f1..1bbb336441d 100644
--- a/crates/router/src/connector/adyen/transformers.rs
+++ b/crates/router/src/connector/adyen/transformers.rs
@@ -2339,7 +2339,8 @@ impl<'a> TryFrom<(&api_models::payments::BankRedirectData, Option<bool>)>
Ok(AdyenPaymentMethod::Trustly)
}
payments::BankRedirectData::Interac { .. }
- | payments::BankRedirectData::Przelewy24 { .. } => {
+ | payments::BankRedirectData::Przelewy24 { .. }
+ | payments::BankRedirectData::OpenBanking { .. } => {
Err(errors::ConnectorError::NotSupported {
message: utils::SELECTED_PAYMENT_METHOD.to_string(),
connector: "Adyen",
diff --git a/crates/router/src/connector/klarna.rs b/crates/router/src/connector/klarna.rs
index 8b7ab0da7f2..4f3aa9be9ca 100644
--- a/crates/router/src/connector/klarna.rs
+++ b/crates/router/src/connector/klarna.rs
@@ -385,6 +385,7 @@ impl
| api_models::enums::PaymentMethodType::PagoEfectivo
| api_models::enums::PaymentMethodType::PermataBankTransfer
| api_models::enums::PaymentMethodType::OpenBankingUk
+ | api_models::enums::PaymentMethodType::OpenBanking
| api_models::enums::PaymentMethodType::PayBright
| api_models::enums::PaymentMethodType::Paypal
| api_models::enums::PaymentMethodType::Pix
diff --git a/crates/router/src/connector/nexinets/transformers.rs b/crates/router/src/connector/nexinets/transformers.rs
index 07488271aea..8ff490d265c 100644
--- a/crates/router/src/connector/nexinets/transformers.rs
+++ b/crates/router/src/connector/nexinets/transformers.rs
@@ -608,6 +608,7 @@ fn get_payment_details_and_product(
| api_models::payments::BankRedirectData::OnlineBankingPoland { .. }
| api_models::payments::BankRedirectData::OnlineBankingSlovakia { .. }
| api_models::payments::BankRedirectData::OpenBankingUk { .. }
+ | api_models::payments::BankRedirectData::OpenBanking { .. }
| api_models::payments::BankRedirectData::Przelewy24 { .. }
| api_models::payments::BankRedirectData::Trustly { .. }
| api_models::payments::BankRedirectData::OnlineBankingFpx { .. }
diff --git a/crates/router/src/connector/nuvei/transformers.rs b/crates/router/src/connector/nuvei/transformers.rs
index 1312eadadf7..baf511cae0b 100644
--- a/crates/router/src/connector/nuvei/transformers.rs
+++ b/crates/router/src/connector/nuvei/transformers.rs
@@ -820,6 +820,7 @@ impl<F>
| payments::BankRedirectData::Trustly { .. }
| payments::BankRedirectData::OnlineBankingFpx { .. }
| payments::BankRedirectData::OnlineBankingThailand { .. }
+ | payments::BankRedirectData::OpenBanking { .. }
| payments::BankRedirectData::OpenBankingUk { .. } => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("nuvei"),
diff --git a/crates/router/src/connector/paypal/transformers.rs b/crates/router/src/connector/paypal/transformers.rs
index a584fe98165..46df4a0b21d 100644
--- a/crates/router/src/connector/paypal/transformers.rs
+++ b/crates/router/src/connector/paypal/transformers.rs
@@ -398,6 +398,7 @@ fn get_payment_source(
| BankRedirectData::OnlineBankingPoland { .. }
| BankRedirectData::OnlineBankingSlovakia { .. }
| BankRedirectData::OpenBankingUk { .. }
+ | BankRedirectData::OpenBanking { .. }
| BankRedirectData::Trustly { .. }
| BankRedirectData::OnlineBankingFpx { .. }
| BankRedirectData::OnlineBankingThailand { .. } => {
diff --git a/crates/router/src/connector/plaid.rs b/crates/router/src/connector/plaid.rs
new file mode 100644
index 00000000000..1d884a22979
--- /dev/null
+++ b/crates/router/src/connector/plaid.rs
@@ -0,0 +1,789 @@
+pub mod transformers;
+
+use std::fmt::Debug;
+
+use common_utils::ext_traits::ByteSliceExt;
+use error_stack::ResultExt;
+use transformers as plaid;
+
+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},
+ transformers::ForeignFrom,
+ ErrorResponse, RequestContent, Response,
+ },
+ utils::BytesExt,
+};
+
+#[derive(Debug, Clone)]
+pub struct Plaid;
+
+impl api::Payment for Plaid {}
+impl api::PaymentSession for Plaid {}
+impl api::ConnectorAccessToken for Plaid {}
+impl api::MandateSetup for Plaid {}
+impl api::PaymentAuthorize for Plaid {}
+impl api::PaymentSync for Plaid {}
+impl api::PaymentCapture for Plaid {}
+impl api::PaymentVoid for Plaid {}
+impl api::Refund for Plaid {}
+impl api::RefundExecute for Plaid {}
+impl api::RefundSync for Plaid {}
+impl api::PaymentToken for Plaid {}
+impl api::PaymentsPostProcessing for Plaid {}
+impl api::ConnectorVerifyWebhookSource for Plaid {}
+
+impl
+ ConnectorIntegration<
+ api::PaymentMethodToken,
+ types::PaymentMethodTokenizationData,
+ types::PaymentsResponseData,
+ > for Plaid
+{
+ // Not Implemented (R)
+}
+
+impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Plaid
+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 auth = self.get_auth_header(&req.connector_auth_type)?;
+ header.append(&mut auth);
+ Ok(header)
+ }
+}
+
+impl ConnectorCommon for Plaid {
+ fn id(&self) -> &'static str {
+ "plaid"
+ }
+
+ fn get_currency_unit(&self) -> api::CurrencyUnit {
+ api::CurrencyUnit::Base
+ }
+
+ fn common_get_content_type(&self) -> &'static str {
+ "application/json"
+ }
+
+ fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str {
+ connectors.plaid.base_url.as_ref()
+ }
+
+ fn get_auth_header(
+ &self,
+ auth_type: &types::ConnectorAuthType,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
+ let auth = plaid::PlaidAuthType::try_from(auth_type)
+ .change_context(errors::ConnectorError::FailedToObtainAuthType)?;
+ let client_id = auth.client_id.into_masked();
+ let secret = auth.secret.into_masked();
+
+ Ok(vec![
+ ("PLAID-CLIENT-ID".to_string(), client_id),
+ ("PLAID-SECRET".to_string(), secret),
+ ])
+ }
+
+ fn build_error_response(
+ &self,
+ res: Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ let response: plaid::PlaidErrorResponse =
+ res.response
+ .parse_struct("PlaidErrorResponse")
+ .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: crate::consts::NO_ERROR_CODE.to_string(),
+ message: response.error_message,
+ reason: response.display_message,
+ attempt_status: None,
+ connector_transaction_id: None,
+ })
+ }
+}
+
+impl ConnectorValidation for Plaid {
+ //TODO: implement functions when support enabled
+}
+
+impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData>
+ for Plaid
+{
+ //TODO: implement sessions flow
+}
+
+impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken>
+ for Plaid
+{
+}
+
+impl
+ ConnectorIntegration<
+ api::SetupMandate,
+ types::SetupMandateRequestData,
+ types::PaymentsResponseData,
+ > for Plaid
+{
+}
+
+impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData>
+ for Plaid
+{
+ 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> {
+ Ok(format!(
+ "{}/payment_initiation/payment/create",
+ self.base_url(connectors)
+ ))
+ }
+
+ fn get_request_body(
+ &self,
+ req: &types::PaymentsAuthorizeRouterData,
+ _connectors: &settings::Connectors,
+ ) -> CustomResult<RequestContent, errors::ConnectorError> {
+ let connector_router_data =
+ plaid::PlaidRouterData::try_from((Some(req.request.amount as f64), req))?;
+ let connector_req = plaid::PlaidPaymentsRequest::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: plaid::PlaidPaymentsResponse = res
+ .response
+ .parse_struct("PlaidPaymentsResponse")
+ .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 Plaid
+{
+ 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_request_body(
+ &self,
+ req: &types::PaymentsSyncRouterData,
+ _connectors: &settings::Connectors,
+ ) -> CustomResult<RequestContent, errors::ConnectorError> {
+ let connector_router_data = plaid::PlaidRouterData::try_from((None, req))?;
+ let connector_req = plaid::PlaidSyncRequest::try_from(&connector_router_data)?;
+ Ok(RequestContent::Json(Box::new(connector_req)))
+ }
+
+ fn get_url(
+ &self,
+ req: &types::PaymentsSyncRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ let _connector_payment_id = req
+ .request
+ .connector_transaction_id
+ .get_connector_transaction_id()
+ .change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
+ Ok(format!(
+ "{}/payment_initiation/payment/get",
+ self.base_url(connectors)
+ ))
+ }
+
+ fn build_request(
+ &self,
+ req: &types::PaymentsSyncRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ 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(
+ &self,
+ data: &types::PaymentsSyncRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
+ res: Response,
+ ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
+ let response: plaid::PlaidSyncResponse = res
+ .response
+ .parse_struct("PlaidSyncResponse")
+ .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::PostProcessing,
+ types::PaymentsPostProcessingData,
+ types::PaymentsResponseData,
+ > for Plaid
+{
+ fn get_headers(
+ &self,
+ req: &types::PaymentsPostProcessingRouterData,
+ 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::PaymentsPostProcessingRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Ok(format!("{}/link/token/create", self.base_url(connectors)))
+ }
+
+ fn get_request_body(
+ &self,
+ req: &types::PaymentsPostProcessingRouterData,
+ _connectors: &settings::Connectors,
+ ) -> CustomResult<RequestContent, errors::ConnectorError> {
+ let connector_router_data = plaid::PlaidRouterData::try_from((None, req))?;
+ let connector_req = plaid::PlaidLinkTokenRequest::try_from(&connector_router_data)?;
+ Ok(RequestContent::Json(Box::new(connector_req)))
+ }
+
+ fn build_request(
+ &self,
+ req: &types::PaymentsPostProcessingRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ Ok(Some(
+ services::RequestBuilder::new()
+ .method(services::Method::Post)
+ .url(&types::PaymentsPostProcessingType::get_url(
+ self, req, connectors,
+ )?)
+ .attach_default_headers()
+ .headers(types::PaymentsPostProcessingType::get_headers(
+ self, req, connectors,
+ )?)
+ .set_body(types::PaymentsPostProcessingType::get_request_body(
+ self, req, connectors,
+ )?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &types::PaymentsPostProcessingRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
+ res: Response,
+ ) -> CustomResult<types::PaymentsPostProcessingRouterData, errors::ConnectorError> {
+ let response: plaid::PlaidLinkTokenResponse = res
+ .response
+ .parse_struct("PlaidLinkTokenResponse")
+ .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 Plaid
+{
+ 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: plaid::PlaidPaymentsResponse = res
+ .response
+ .parse_struct("Plaid 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 Plaid
+{
+}
+
+impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> for Plaid {
+ 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 =
+ plaid::PlaidRouterData::try_from((Some(req.request.refund_amount as f64), req))?;
+ let connector_req = plaid::PlaidRefundRequest::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: plaid::RefundResponse = res
+ .response
+ .parse_struct("plaid 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 Plaid {
+ 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: plaid::RefundResponse = res
+ .response
+ .parse_struct("plaid 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)
+ }
+}
+
+impl
+ ConnectorIntegration<
+ api::VerifyWebhookSource,
+ types::VerifyWebhookSourceRequestData,
+ types::VerifyWebhookSourceResponseData,
+ > for Plaid
+{
+ fn get_headers(
+ &self,
+ req: &types::RouterData<
+ api::VerifyWebhookSource,
+ types::VerifyWebhookSourceRequestData,
+ types::VerifyWebhookSourceResponseData,
+ >,
+ 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::RouterData<
+ api::VerifyWebhookSource,
+ types::VerifyWebhookSourceRequestData,
+ types::VerifyWebhookSourceResponseData,
+ >,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Ok(format!(
+ "{}/webhook_verification_key/get",
+ self.base_url(connectors)
+ ))
+ }
+
+ fn build_request(
+ &self,
+ req: &types::VerifyWebhookSourceRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ let request = services::RequestBuilder::new()
+ .method(services::Method::Post)
+ .url(&types::VerifyWebhookSourceType::get_url(
+ self, req, connectors,
+ )?)
+ .headers(types::VerifyWebhookSourceType::get_headers(
+ self, req, connectors,
+ )?)
+ .set_body(types::VerifyWebhookSourceType::get_request_body(
+ self, req, connectors,
+ )?)
+ .build();
+
+ Ok(Some(request))
+ }
+
+ fn get_request_body(
+ &self,
+ req: &types::RouterData<
+ api::VerifyWebhookSource,
+ types::VerifyWebhookSourceRequestData,
+ types::VerifyWebhookSourceResponseData,
+ >,
+ _connectors: &settings::Connectors,
+ ) -> CustomResult<RequestContent, errors::ConnectorError> {
+ let connector_req = plaid::PlaidWebhookVerificationRequest::try_from(&req.request)?;
+ Ok(RequestContent::Json(Box::new(connector_req)))
+ }
+
+ fn handle_response(
+ &self,
+ data: &types::VerifyWebhookSourceRouterData,
+ event_builder: Option<&mut ConnectorEvent>,
+ res: Response,
+ ) -> CustomResult<types::VerifyWebhookSourceRouterData, errors::ConnectorError> {
+ let response: plaid::PlaidWebhookVerificationResponse = res
+ .response
+ .parse_struct("PlaidWebhookVerificationResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ plaid::process_plaid_jwt_header(&data.request, &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,
+ })
+ }
+ 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 Plaid {
+ fn get_webhook_object_reference_id(
+ &self,
+ request: &api::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<api::webhooks::ObjectReferenceId, errors::ConnectorError> {
+ let payload: plaid::PlaidPaymentsWebhookBody = request
+ .body
+ .parse_struct("PlaidPaymentsWebhookBody")
+ .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
+
+ Ok(api::ObjectReferenceId::PaymentId(
+ api::PaymentIdType::ConnectorTransactionId(payload.payment_id),
+ ))
+ }
+
+ fn get_webhook_event_type(
+ &self,
+ request: &api::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> {
+ let payload: plaid::PlaidPaymentsWebhookBody = request
+ .body
+ .parse_struct("PlaidPaymentsWebhookBody")
+ .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
+
+ Ok(api::IncomingWebhookEvent::foreign_from(
+ payload.new_payment_status,
+ ))
+ }
+
+ fn get_webhook_resource_object(
+ &self,
+ request: &api::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
+ let payload: plaid::PlaidPaymentsWebhookBody = request
+ .body
+ .parse_struct("PlaidPaymentsWebhookBody")
+ .change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?;
+
+ Ok(Box::new(payload))
+ }
+}
diff --git a/crates/router/src/connector/plaid/transformers.rs b/crates/router/src/connector/plaid/transformers.rs
new file mode 100644
index 00000000000..81c0c7dde05
--- /dev/null
+++ b/crates/router/src/connector/plaid/transformers.rs
@@ -0,0 +1,678 @@
+use actix_http::header::HeaderMap;
+use common_enums::Currency;
+use error_stack::{IntoReport, ResultExt};
+use jsonwebtoken;
+use masking::{PeekInterface, Secret};
+use ring::digest;
+use serde::{Deserialize, Serialize};
+
+use crate::{
+ core::errors,
+ types::{self, api, storage::enums, transformers::ForeignFrom},
+ utils::ext_traits::OptionExt,
+};
+
+const PLAID_VERIFICATION_HEADER: &str = "Plaid-Verification";
+
+//TODO: Fill the struct with respective fields
+pub struct PlaidRouterData<T> {
+ pub amount: Option<f64>, // The type of amount that a connector accepts, for example, String, i64, f64, etc.
+ pub router_data: T,
+}
+
+impl<T> TryFrom<(Option<f64>, T)> for PlaidRouterData<T> {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from((amount, item): (Option<f64>, 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,
+ })
+ }
+}
+
+#[derive(Default, Debug, Serialize)]
+pub struct PlaidPaymentsRequest {
+ amount: PlaidAmount,
+ recipient_id: String,
+ reference: String,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ schedule: Option<PlaidSchedule>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ options: Option<PlaidOptions>,
+}
+
+#[derive(Default, Debug, Serialize, Deserialize)]
+pub struct PlaidAmount {
+ currency: Currency,
+ value: f64,
+}
+
+#[derive(Default, Debug, Serialize, Deserialize)]
+pub struct PlaidSchedule {
+ interval: String,
+ interval_execution_day: String,
+ start_date: String,
+ end_date: Option<String>,
+ adjusted_start_date: Option<String>,
+}
+
+#[derive(Default, Debug, Serialize, Deserialize)]
+pub struct PlaidOptions {
+ request_refund_details: bool,
+ iban: Option<String>,
+ bacs: Option<PlaidBacs>,
+ scheme: String,
+}
+
+#[derive(Default, Debug, Serialize, Deserialize)]
+pub struct PlaidBacs {
+ acount: Secret<String>,
+ sort_code: Secret<String>,
+}
+
+#[derive(Default, Debug, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub struct PlaidLinkTokenRequest {
+ client_name: String,
+ country_codes: Vec<String>,
+ language: String,
+ products: Vec<String>,
+ user: User,
+ payment_initiation: PlaidPaymentInitiation,
+}
+
+#[derive(Default, Debug, Serialize, Deserialize)]
+pub struct User {
+ pub client_user_id: String,
+}
+
+#[derive(Default, Debug, Serialize, Deserialize)]
+pub struct PlaidPaymentInitiation {
+ payment_id: String,
+}
+
+impl TryFrom<&PlaidRouterData<&types::PaymentsAuthorizeRouterData>> for PlaidPaymentsRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: &PlaidRouterData<&types::PaymentsAuthorizeRouterData>,
+ ) -> Result<Self, Self::Error> {
+ match item.router_data.request.payment_method_data.clone() {
+ api::PaymentMethodData::BankRedirect(ref bank) => match bank {
+ api_models::payments::BankRedirectData::OpenBanking { .. } => {
+ let amount =
+ item.amount
+ .ok_or(errors::ConnectorError::MissingRequiredField {
+ field_name: "amount",
+ })?;
+ let currency = item.router_data.request.currency;
+ let reference = "Some ref".to_string();
+ let recipient_val = item
+ .router_data
+ .connector_meta_data
+ .as_ref()
+ .ok_or(errors::ConnectorError::MissingRequiredField {
+ field_name: "connector_customer",
+ })?
+ .peek()
+ .clone();
+
+ let recipient_type =
+ serde_json::from_value::<types::MerchantRecipientData>(recipient_val)
+ .into_report()
+ .change_context(errors::ConnectorError::ParsingFailed)?;
+ let recipient_id = match recipient_type {
+ types::MerchantRecipientData::RecipientId(id) => Ok(id.peek().to_string()),
+ _ => Err(errors::ConnectorError::NotSupported {
+ message: "recipient_id not found, other methods".to_string(),
+ connector: "plaid",
+ }),
+ }
+ .into_report()?;
+
+ Ok(Self {
+ amount: PlaidAmount {
+ currency,
+ value: amount,
+ },
+ reference,
+ recipient_id,
+ schedule: None,
+ options: None,
+ })
+ }
+ _ => Err(
+ errors::ConnectorError::NotImplemented("Payment method type".to_string())
+ .into(),
+ ),
+ },
+ _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()),
+ }
+ }
+}
+
+impl TryFrom<&PlaidRouterData<&types::PaymentsSyncRouterData>> for PlaidSyncRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: &PlaidRouterData<&types::PaymentsSyncRouterData>,
+ ) -> Result<Self, Self::Error> {
+ match item.router_data.request.connector_transaction_id {
+ types::ResponseId::ConnectorTransactionId(ref id) => Ok(Self {
+ payment_id: id.clone(),
+ }),
+ _ => Err(
+ errors::ConnectorError::NotImplemented("ResponseId for Plaid".to_string()).into(),
+ ),
+ }
+ }
+}
+
+impl TryFrom<&PlaidRouterData<&types::PaymentsPostProcessingRouterData>> for PlaidLinkTokenRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: &PlaidRouterData<&types::PaymentsPostProcessingRouterData>,
+ ) -> Result<Self, Self::Error> {
+ match item.router_data.request.payment_method_data.clone() {
+ api::PaymentMethodData::BankRedirect(ref bank) => match bank {
+ api_models::payments::BankRedirectData::OpenBanking { .. } => Ok(Self {
+ // discuss this with folks
+ client_name: "Hyperswitch".to_string(),
+ country_codes: vec!["GB".to_string()],
+ language: "en".to_string(),
+ products: vec!["payment_initiation".to_string()],
+ user: User {
+ client_user_id: item
+ .router_data
+ .request
+ .customer_id
+ .clone()
+ .unwrap_or("default cust".to_string()),
+ },
+ payment_initiation: PlaidPaymentInitiation {
+ payment_id: item
+ .router_data
+ .request
+ .connector_transaction_id
+ .clone()
+ .ok_or(errors::ConnectorError::MissingRequiredField {
+ field_name: "connector_transaction_id",
+ })?,
+ },
+ }),
+ _ => Err(
+ errors::ConnectorError::NotImplemented("Payment method type".to_string())
+ .into(),
+ ),
+ },
+ _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()),
+ }
+ }
+}
+
+//TODO: Fill the struct with respective fields
+// Auth Struct
+pub struct PlaidAuthType {
+ pub client_id: Secret<String>,
+ pub secret: Secret<String>,
+}
+
+impl TryFrom<&types::ConnectorAuthType> for PlaidAuthType {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
+ match auth_type {
+ types::ConnectorAuthType::OpenBankingAuth {
+ api_key,
+ key1,
+ ..
+ } => Ok(Self {
+ client_id: api_key.to_owned(),
+ secret: key1.to_owned(),
+ }),
+ _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
+ }
+ }
+}
+// PaymentsResponse
+//TODO: Append the remaining status flags
+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
+#[derive(strum::Display)]
+pub enum PlaidPaymentStatus {
+ PaymentStatusInputNeeded,
+ PaymentStatusInitiated,
+ PaymentStatusInsuficientFunds,
+ PaymentStatusFailed,
+ PaymentStatusBlcoked,
+ PaymentStatusCancelled,
+ PaymentStatusExecuted,
+ PaymentStatusSettled,
+ PaymentStatusEstablished,
+ PaymentStatusRejected,
+ #[default]
+ PaymentStatusAuthorising,
+}
+
+impl From<PlaidPaymentStatus> for enums::AttemptStatus {
+ fn from(item: PlaidPaymentStatus) -> Self {
+ match item {
+ // Double check these with someone
+ PlaidPaymentStatus::PaymentStatusAuthorising => Self::Authorizing,
+ PlaidPaymentStatus::PaymentStatusBlcoked => Self::AuthorizationFailed,
+ PlaidPaymentStatus::PaymentStatusCancelled => Self::Voided,
+ PlaidPaymentStatus::PaymentStatusEstablished => Self::Authorized,
+ PlaidPaymentStatus::PaymentStatusExecuted => Self::Authorized,
+ PlaidPaymentStatus::PaymentStatusFailed => Self::Failure,
+ PlaidPaymentStatus::PaymentStatusInitiated => Self::AuthenticationPending,
+ PlaidPaymentStatus::PaymentStatusInputNeeded => Self::AuthenticationPending,
+ PlaidPaymentStatus::PaymentStatusInsuficientFunds => Self::AuthorizationFailed,
+ PlaidPaymentStatus::PaymentStatusRejected => Self::AuthorizationFailed,
+ PlaidPaymentStatus::PaymentStatusSettled => Self::Charged,
+ }
+ }
+}
+
+//TODO: Fill the struct with respective fields
+#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
+pub struct PlaidPaymentsResponse {
+ status: PlaidPaymentStatus,
+ payment_id: String,
+}
+
+impl<F, T>
+ TryFrom<types::ResponseRouterData<F, PlaidPaymentsResponse, T, types::PaymentsResponseData>>
+ for types::RouterData<F, T, types::PaymentsResponseData>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: types::ResponseRouterData<F, PlaidPaymentsResponse, 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.payment_id.clone(),
+ ),
+ redirection_data: None,
+ mandate_reference: None,
+ connector_metadata: None,
+ network_txn_id: None,
+ connector_response_reference_id: Some(item.response.payment_id),
+ incremental_authorization_allowed: None,
+ }),
+ ..item.data
+ })
+ }
+}
+
+#[derive(Default, Debug, Serialize, Deserialize)]
+pub struct PlaidLinkTokenResponse {
+ link_token: String,
+}
+
+impl<F, T>
+ TryFrom<types::ResponseRouterData<F, PlaidLinkTokenResponse, T, types::PaymentsResponseData>>
+ for types::RouterData<F, T, types::PaymentsResponseData>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: types::ResponseRouterData<F, PlaidLinkTokenResponse, T, types::PaymentsResponseData>,
+ ) -> Result<Self, Self::Error> {
+ let session_token = Some(api::OpenBankingSessionToken {
+ open_banking_session_token: item.response.link_token,
+ });
+
+ Ok(Self {
+ status: enums::AttemptStatus::AuthenticationPending,
+ response: Ok(types::PaymentsResponseData::PostProcessingResponse { session_token }),
+ ..item.data
+ })
+ }
+}
+
+#[derive(Default, Debug, Serialize, Deserialize)]
+pub struct PlaidSyncRequest {
+ payment_id: String,
+}
+
+#[derive(Default, Debug, Serialize, Deserialize)]
+pub struct PlaidSyncResponse {
+ payment_id: String,
+ amount: PlaidAmount,
+ status: PlaidPaymentStatus,
+ recipient_id: String,
+ reference: String,
+ last_status_update: String,
+ adjusted_reference: Option<String>,
+ schedule: Option<PlaidSchedule>,
+ iban: Option<String>,
+ bacs: Option<PlaidBacs>,
+ scheme: Option<String>,
+ adjusted_scheme: Option<String>,
+ request_id: String,
+ // TODO: add refund related objects
+}
+
+impl<F, T> TryFrom<types::ResponseRouterData<F, PlaidSyncResponse, T, types::PaymentsResponseData>>
+ for types::RouterData<F, T, types::PaymentsResponseData>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: types::ResponseRouterData<F, PlaidSyncResponse, T, types::PaymentsResponseData>,
+ ) -> Result<Self, Self::Error> {
+ let status = enums::AttemptStatus::from(item.response.status.clone());
+ Ok(Self {
+ status,
+ response: if is_payment_failure(status) {
+ Err(types::ErrorResponse {
+ code: item.response.status.clone().to_string(),
+ message: item.response.status.clone().to_string(),
+ reason: Some(item.response.status.to_string()),
+ status_code: item.http_code,
+ attempt_status: None,
+ connector_transaction_id: Some(item.response.payment_id),
+ })
+ } else {
+ Ok(types::PaymentsResponseData::TransactionResponse {
+ resource_id: types::ResponseId::ConnectorTransactionId(
+ item.response.payment_id.clone(),
+ ),
+ redirection_data: None,
+ mandate_reference: None,
+ connector_metadata: None,
+ network_txn_id: None,
+ connector_response_reference_id: Some(item.response.payment_id),
+ incremental_authorization_allowed: None,
+ })
+ },
+ ..item.data
+ })
+ }
+}
+
+// TODO: Fill the struct with respective fields
+// REFUND :
+// Type definition for RefundRequest
+#[derive(Default, Debug, Serialize)]
+pub struct PlaidRefundRequest {
+ pub amount: f64,
+}
+
+impl<F> TryFrom<&PlaidRouterData<&types::RefundsRouterData<F>>> for PlaidRefundRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(item: &PlaidRouterData<&types::RefundsRouterData<F>>) -> Result<Self, Self::Error> {
+ Ok(Self {
+ amount: item
+ .amount
+ .ok_or(errors::ConnectorError::MissingRequiredField {
+ field_name: "amount",
+ })?,
+ })
+ }
+}
+
+// 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
+ })
+ }
+}
+
+#[derive(Default, Debug, Serialize, Deserialize)]
+pub struct PlaidPaymentsWebhookBody {
+ pub webhook_type: String,
+ pub webhook_code: String,
+ pub payment_id: String,
+ pub new_payment_status: PlaidPaymentStatus,
+ pub old_payment_status: PlaidPaymentStatus,
+ pub original_reference: String,
+ pub adjusted_reference: String,
+ pub original_start_date: String,
+ pub adjusted_start_date: String,
+ pub timestamp: String,
+ pub environment: String,
+}
+
+impl ForeignFrom<PlaidPaymentStatus> for api::IncomingWebhookEvent {
+ fn foreign_from(status: PlaidPaymentStatus) -> Self {
+ match status {
+ // Double check these with someone
+ PlaidPaymentStatus::PaymentStatusAuthorising => Self::PaymentIntentProcessing,
+ PlaidPaymentStatus::PaymentStatusBlcoked => Self::PaymentIntentAuthorizationFailure,
+ PlaidPaymentStatus::PaymentStatusCancelled => Self::PaymentIntentCancelled,
+ PlaidPaymentStatus::PaymentStatusEstablished => Self::PaymentIntentAuthorizationSuccess,
+ PlaidPaymentStatus::PaymentStatusExecuted => Self::PaymentIntentSuccess,
+ PlaidPaymentStatus::PaymentStatusFailed => Self::PaymentIntentFailure,
+ PlaidPaymentStatus::PaymentStatusInitiated => Self::PaymentIntentAuthorizationSuccess,
+ PlaidPaymentStatus::PaymentStatusInputNeeded => Self::PaymentActionRequired,
+ PlaidPaymentStatus::PaymentStatusInsuficientFunds => Self::PaymentIntentFailure,
+ PlaidPaymentStatus::PaymentStatusRejected => Self::PaymentIntentFailure,
+ PlaidPaymentStatus::PaymentStatusSettled => Self::PaymentIntentSuccess,
+ }
+ }
+}
+
+#[derive(Default, Debug, Serialize, Deserialize)]
+pub struct PlaidWebhookVerificationRequest {
+ pub key_id: String,
+}
+
+#[derive(Default, Debug, Serialize, Deserialize)]
+pub struct PlaidJWK {
+ kid: String,
+ alg: String,
+ created_at: i64,
+ expired_at: Option<i64>,
+ pub x: String,
+ pub y: String,
+ #[serde(rename = "use")]
+ _use: String,
+ kty: String,
+ crv: String,
+}
+
+#[derive(Default, Debug, Serialize, Deserialize)]
+pub struct PlaidWebhookVerificationResponse {
+ key: PlaidJWK,
+}
+
+#[derive(Default, Debug, Serialize, Deserialize)]
+struct PlaidJWTPayload {
+ iat: i64,
+ request_body_sha256: String,
+}
+
+impl TryFrom<&types::VerifyWebhookSourceRequestData> for PlaidWebhookVerificationRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(req: &types::VerifyWebhookSourceRequestData) -> Result<Self, Self::Error> {
+ let kid = get_data_from_verification_header(&req.webhook_headers)?;
+
+ Ok(Self { key_id: kid })
+ }
+}
+
+impl
+ TryFrom<
+ types::ResponseRouterData<
+ api::VerifyWebhookSource,
+ PlaidWebhookVerificationResponse,
+ types::VerifyWebhookSourceRequestData,
+ types::VerifyWebhookSourceResponseData,
+ >,
+ > for types::VerifyWebhookSourceRouterData
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: types::ResponseRouterData<
+ api::VerifyWebhookSource,
+ PlaidWebhookVerificationResponse,
+ types::VerifyWebhookSourceRequestData,
+ types::VerifyWebhookSourceResponseData,
+ >,
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ response: Ok(types::VerifyWebhookSourceResponseData {
+ verify_webhook_status: types::VerifyWebhookStatus::SourceVerified,
+ }),
+ ..item.data
+ })
+ }
+}
+#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "snake_case")]
+pub struct PlaidErrorResponse {
+ pub display_message: Option<String>,
+ pub error_code: Option<String>,
+ pub error_message: String,
+ pub error_type: Option<String>,
+}
+
+fn is_payment_failure(status: enums::AttemptStatus) -> bool {
+ match status {
+ common_enums::AttemptStatus::AuthenticationFailed
+ | common_enums::AttemptStatus::AuthorizationFailed
+ | common_enums::AttemptStatus::CaptureFailed
+ | common_enums::AttemptStatus::VoidFailed
+ | common_enums::AttemptStatus::Failure => true,
+ common_enums::AttemptStatus::Started
+ | common_enums::AttemptStatus::RouterDeclined
+ | common_enums::AttemptStatus::AuthenticationPending
+ | common_enums::AttemptStatus::AuthenticationSuccessful
+ | common_enums::AttemptStatus::Authorized
+ | common_enums::AttemptStatus::Charged
+ | common_enums::AttemptStatus::Authorizing
+ | common_enums::AttemptStatus::CodInitiated
+ | common_enums::AttemptStatus::Voided
+ | common_enums::AttemptStatus::VoidInitiated
+ | common_enums::AttemptStatus::CaptureInitiated
+ | common_enums::AttemptStatus::AutoRefunded
+ | common_enums::AttemptStatus::PartialCharged
+ | common_enums::AttemptStatus::PartialChargedAndChargeable
+ | common_enums::AttemptStatus::Unresolved
+ | common_enums::AttemptStatus::Pending
+ | common_enums::AttemptStatus::PaymentMethodAwaited
+ | common_enums::AttemptStatus::ConfirmationAwaited
+ | common_enums::AttemptStatus::DeviceDataCollectionPending => false,
+ }
+}
+
+fn get_data_from_verification_header(
+ headers: &HeaderMap,
+) -> Result<String, error_stack::Report<errors::ConnectorError>> {
+ let plaid_header = headers
+ .get(PLAID_VERIFICATION_HEADER)
+ .get_required_value(PLAID_VERIFICATION_HEADER)
+ .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?
+ .to_str()
+ .into_report()
+ .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)
+ .attach_printable("Failed to convert JWT token to string")?;
+
+ let jwt_header = jsonwebtoken::decode_header(plaid_header)
+ .into_report()
+ .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)
+ .attach_printable("Failed to get JWT Header for Plaid")?;
+
+ jwt_header
+ .kid
+ .ok_or(errors::ConnectorError::WebhookSourceVerificationFailed)
+ .into_report()
+ .attach_printable("Failed to get kid from JWT Header for Plaid")
+}
+
+pub fn process_plaid_jwt_header(
+ req: &types::VerifyWebhookSourceRequestData,
+ res: &PlaidWebhookVerificationResponse,
+) -> Result<(), error_stack::Report<errors::ConnectorError>> {
+ let plaid_header = req
+ .webhook_headers
+ .get(PLAID_VERIFICATION_HEADER)
+ .get_required_value(PLAID_VERIFICATION_HEADER)
+ .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?
+ .to_str()
+ .into_report()
+ .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)
+ .attach_printable("Failed to convert JWT token to string")?;
+
+ let key = jsonwebtoken::DecodingKey::from_ec_components(&res.key.x, &res.key.y)
+ .into_report()
+ .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)
+ .attach_printable("Failed to from Decoding key for JWT token")?;
+
+ let decoded = jsonwebtoken::decode::<PlaidJWTPayload>(
+ plaid_header,
+ &key,
+ &jsonwebtoken::Validation::new(jsonwebtoken::Algorithm::ES256),
+ )
+ .into_report()
+ .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)
+ .attach_printable("Failed to validate JWT token")?;
+
+ let body_value = hex::decode(decoded.claims.request_body_sha256)
+ .into_report()
+ .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)
+ .attach_printable("Failed to hex-decode plaid webhook request_body_sha256")?;
+
+ let payload_digest = digest::digest(&digest::SHA256, req.webhook_body.as_slice());
+
+ if payload_digest.as_ref() != body_value.as_slice() {
+ return Err(errors::ConnectorError::WebhookSourceVerificationFailed.into());
+ }
+
+ Ok(())
+}
diff --git a/crates/router/src/connector/shift4/transformers.rs b/crates/router/src/connector/shift4/transformers.rs
index 97c19c49af8..7d4ee582485 100644
--- a/crates/router/src/connector/shift4/transformers.rs
+++ b/crates/router/src/connector/shift4/transformers.rs
@@ -411,6 +411,7 @@ impl TryFrom<&payments::BankRedirectData> for PaymentMethodType {
| payments::BankRedirectData::OnlineBankingPoland { .. }
| payments::BankRedirectData::OnlineBankingSlovakia { .. }
| payments::BankRedirectData::OpenBankingUk { .. }
+ | payments::BankRedirectData::OpenBanking { .. }
| payments::BankRedirectData::OnlineBankingFpx { .. }
| payments::BankRedirectData::OnlineBankingThailand { .. } => {
Err(errors::ConnectorError::NotImplemented(
diff --git a/crates/router/src/connector/square/transformers.rs b/crates/router/src/connector/square/transformers.rs
index 1e5501575ad..dfa5c509cc3 100644
--- a/crates/router/src/connector/square/transformers.rs
+++ b/crates/router/src/connector/square/transformers.rs
@@ -305,15 +305,7 @@ impl TryFrom<&types::ConnectorAuthType> for SquareAuthType {
api_key: api_key.to_owned(),
key1: key1.to_owned(),
}),
-
- types::ConnectorAuthType::HeaderKey { .. }
- | types::ConnectorAuthType::SignatureKey { .. }
- | types::ConnectorAuthType::MultiAuthKey { .. }
- | types::ConnectorAuthType::CurrencyAuthKey { .. }
- | types::ConnectorAuthType::TemporaryAuth { .. }
- | types::ConnectorAuthType::NoKey { .. } => {
- Err(errors::ConnectorError::FailedToObtainAuthType.into())
- }
+ _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs
index d08f28d1a84..d5a1a58ec0f 100644
--- a/crates/router/src/connector/stripe/transformers.rs
+++ b/crates/router/src/connector/stripe/transformers.rs
@@ -654,6 +654,7 @@ impl TryFrom<enums::PaymentMethodType> for StripePaymentMethodType {
| enums::PaymentMethodType::OnlineBankingPoland
| enums::PaymentMethodType::OnlineBankingSlovakia
| enums::PaymentMethodType::OpenBankingUk
+ | enums::PaymentMethodType::OpenBanking
| enums::PaymentMethodType::PagoEfectivo
| enums::PaymentMethodType::PayBright
| enums::PaymentMethodType::Pse
@@ -952,6 +953,7 @@ impl TryFrom<&payments::BankRedirectData> for StripePaymentMethodType {
| payments::BankRedirectData::OnlineBankingSlovakia { .. }
| payments::BankRedirectData::OnlineBankingThailand { .. }
| payments::BankRedirectData::OpenBankingUk { .. }
+ | payments::BankRedirectData::OpenBanking { .. }
| payments::BankRedirectData::Trustly { .. } => {
Err(errors::ConnectorError::NotSupported {
message: connector_util::SELECTED_PAYMENT_METHOD.to_string(),
@@ -1183,6 +1185,7 @@ impl TryFrom<(&payments::BankRedirectData, Option<bool>)> for StripeBillingAddre
| payments::BankRedirectData::Trustly { .. }
| payments::BankRedirectData::OnlineBankingFpx { .. }
| payments::BankRedirectData::OnlineBankingThailand { .. }
+ | payments::BankRedirectData::OpenBanking { .. }
| payments::BankRedirectData::OpenBankingUk { .. } => Ok(Self::default()),
}
}
@@ -1680,6 +1683,7 @@ impl TryFrom<&payments::BankRedirectData> for StripePaymentMethodData {
| payments::BankRedirectData::OnlineBankingSlovakia { .. }
| payments::BankRedirectData::OnlineBankingThailand { .. }
| payments::BankRedirectData::OpenBankingUk { .. }
+ | payments::BankRedirectData::OpenBanking { .. }
| payments::BankRedirectData::Trustly { .. } => {
Err(errors::ConnectorError::NotSupported {
message: connector_util::SELECTED_PAYMENT_METHOD.to_string(),
diff --git a/crates/router/src/connector/trustpay/transformers.rs b/crates/router/src/connector/trustpay/transformers.rs
index 79850decb69..1fa9a4aebe3 100644
--- a/crates/router/src/connector/trustpay/transformers.rs
+++ b/crates/router/src/connector/trustpay/transformers.rs
@@ -17,6 +17,7 @@ use crate::{
},
consts,
core::errors,
+ headers::NONCE,
services,
types::{self, api, storage::enums, BrowserInformation},
};
@@ -246,6 +247,7 @@ impl TryFrom<&BankRedirectData> for TrustpayPaymentMethod {
| api_models::payments::BankRedirectData::OnlineBankingPoland { .. }
| api_models::payments::BankRedirectData::OnlineBankingSlovakia { .. }
| api_models::payments::BankRedirectData::OpenBankingUk { .. }
+ | api_models::payments::BankRedirectData::OpenBanking { .. }
| api_models::payments::BankRedirectData::Przelewy24 { .. }
| api_models::payments::BankRedirectData::Trustly { .. }
| api_models::payments::BankRedirectData::OnlineBankingFpx { .. }
diff --git a/crates/router/src/connector/volt/transformers.rs b/crates/router/src/connector/volt/transformers.rs
index b7c9a6826ce..c1eb52a1a19 100644
--- a/crates/router/src/connector/volt/transformers.rs
+++ b/crates/router/src/connector/volt/transformers.rs
@@ -133,6 +133,7 @@ impl TryFrom<&VoltRouterData<&types::PaymentsAuthorizeRouterData>> for VoltPayme
| api_models::payments::BankRedirectData::Sofort { .. }
| api_models::payments::BankRedirectData::Trustly { .. }
| api_models::payments::BankRedirectData::OnlineBankingFpx { .. }
+ | api_models::payments::BankRedirectData::OpenBanking { .. }
| api_models::payments::BankRedirectData::OnlineBankingThailand { .. } => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Volt"),
diff --git a/crates/router/src/connector/worldline/transformers.rs b/crates/router/src/connector/worldline/transformers.rs
index 1eb22fc52d2..caca9a41770 100644
--- a/crates/router/src/connector/worldline/transformers.rs
+++ b/crates/router/src/connector/worldline/transformers.rs
@@ -417,6 +417,7 @@ fn make_bank_redirect_request(
| payments::BankRedirectData::OnlineBankingPoland { .. }
| payments::BankRedirectData::OnlineBankingSlovakia { .. }
| payments::BankRedirectData::OpenBankingUk { .. }
+ | payments::BankRedirectData::OpenBanking { .. }
| payments::BankRedirectData::Przelewy24 { .. }
| payments::BankRedirectData::Sofort { .. }
| payments::BankRedirectData::Trustly { .. }
diff --git a/crates/router/src/connector/zen/transformers.rs b/crates/router/src/connector/zen/transformers.rs
index ebea61304a1..5497969ccc1 100644
--- a/crates/router/src/connector/zen/transformers.rs
+++ b/crates/router/src/connector/zen/transformers.rs
@@ -737,6 +737,7 @@ impl TryFrom<&api_models::payments::BankRedirectData> for ZenPaymentsRequest {
| api_models::payments::BankRedirectData::OnlineBankingPoland { .. }
| api_models::payments::BankRedirectData::OnlineBankingSlovakia { .. }
| api_models::payments::BankRedirectData::OpenBankingUk { .. }
+ | api_models::payments::BankRedirectData::OpenBanking { .. }
| api_models::payments::BankRedirectData::OnlineBankingFpx { .. }
| api_models::payments::BankRedirectData::OnlineBankingThailand { .. } => {
Err(errors::ConnectorError::NotImplemented(
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index 0eaabf8652c..87397879dde 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -10,24 +10,28 @@ use common_utils::{
ext_traits::{AsyncExt, ConfigExt, Encode, ValueExt},
pii,
};
-use diesel_models::configs;
+use diesel_models::{configs, encryption};
use error_stack::{report, FutureExt, IntoReport, ResultExt};
use futures::future::try_join_all;
use masking::{PeekInterface, Secret};
-use pm_auth::connector::plaid::transformers::PlaidAuthType;
+use pm_auth::{connector::plaid::transformers::PlaidAuthType, types as pm_auth_types};
+use regex::Regex;
+use serde_json;
use uuid::Uuid;
use crate::{
consts,
core::{
errors::{self, RouterResponse, RouterResult, StorageErrorExt},
+ payment_methods::{cards, transformers},
payments::helpers,
+ pm_auth::helpers::PaymentAuthConnectorDataExt,
routing::helpers as routing_helpers,
utils as core_utils,
},
db::StorageInterface,
routes::{metrics, AppState},
- services::{self, api as service_api},
+ services::{self, api as service_api, pm_auth as payment_initiation_service},
types::{
self, api,
domain::{
@@ -786,7 +790,9 @@ pub async fn create_payment_connector(
api_enums::convert_authentication_connector(req.connector_name.to_string().as_str());
if pm_auth_connector.is_some() {
- if req.connector_type != api_enums::ConnectorType::PaymentMethodAuth {
+ if req.connector_type != api_enums::ConnectorType::PaymentMethodAuth
+ && req.connector_type != api_enums::ConnectorType::PaymentProcessor
+ {
return Err(errors::ApiErrorResponse::InvalidRequestData {
message: "Invalid connector type given".to_string(),
})
@@ -852,6 +858,16 @@ pub async fn create_payment_connector(
expected_format: "auth_type and api_key".to_string(),
})?;
+ let auth = process_open_banking_connectors(
+ &state,
+ merchant_id.as_str(),
+ &key_store,
+ auth,
+ &req.connector_type,
+ &req.connector_name,
+ )
+ .await?;
+
validate_auth_and_metadata_type(req.connector_name, &auth, &req.metadata).map_err(|err| {
match *err.current_context() {
errors::ConnectorError::InvalidConnectorName => {
@@ -892,7 +908,7 @@ pub async fn create_payment_connector(
let (connector_status, disabled) = validate_status_and_disabled(
req.status,
req.disabled,
- auth,
+ auth.clone(),
// The validate_status_and_disabled function will use this value only
// when the status can be active. So we are passing this as fallback.
api_enums::ConnectorStatus::Active,
@@ -912,17 +928,19 @@ pub async fn create_payment_connector(
}
}
+ let connector_auth = serde_json::to_value(auth)
+ .into_report()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed while encoding to serde_json::Value, ConnectorAuthType")?;
+ let conn_auth = Secret::new(connector_auth);
+
let merchant_connector_account = domain::MerchantConnectorAccount {
merchant_id: merchant_id.to_string(),
connector_type: req.connector_type,
connector_name: req.connector_name.to_string(),
merchant_connector_id: utils::generate_id(consts::ID_LENGTH, "mca"),
connector_account_details: domain_types::encrypt(
- req.connector_account_details.ok_or(
- errors::ApiErrorResponse::MissingRequiredField {
- field_name: "connector_account_details",
- },
- )?,
+ conn_auth,
key_store.key.peek(),
)
.await
@@ -1987,3 +2005,288 @@ pub fn validate_status_and_disabled(
Ok((connector_status, disabled))
}
+
+async fn process_open_banking_connectors(
+ state: &AppState,
+ merchant_id: &str,
+ key_store: &domain::MerchantKeyStore,
+ auth: types::ConnectorAuthType,
+ connector_type: &api_enums::ConnectorType,
+ connector: &api_enums::Connector,
+) -> RouterResult<types::ConnectorAuthType> {
+ match &auth {
+ types::ConnectorAuthType::OpenBankingAuth {
+ api_key,
+ key1,
+ merchant_data,
+ } => {
+ // incorporate a connector check as well
+ if connector_type != &api_enums::ConnectorType::PaymentProcessor {
+ return Err(errors::ApiErrorResponse::InvalidConnectorConfiguration {
+ config: "OpenBankingAuth type needs to be coupled with a payment connector"
+ .to_string(),
+ }
+ .into());
+ }
+
+ let new_auth = match merchant_data {
+ types::MerchantRecipientData::AccountData(acc_data) => {
+ validate_bank_account_data(acc_data)?;
+
+ let connector_name = api_enums::Connector::to_string(connector);
+
+ let locker_based_connector_list =
+ state.conf.locker_open_banking_connectors.clone();
+ let contains = locker_based_connector_list
+ .connector_list
+ .get(connector_name.as_str());
+
+ let recipient_id = if let Some(_conn) = contains {
+ locker_recipient_create_call(state, merchant_id, key_store, acc_data).await
+ } else {
+ connector_recipient_create_call(
+ state,
+ merchant_id,
+ connector_name,
+ &auth,
+ acc_data,
+ )
+ .await
+ }
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("failed to get recipient_id")?;
+
+ // data.merchant_data = api_models::admin::MerchantRecipientData::RecipientID(
+ // Secret::new(recipient_id),
+ // );
+
+ types::ConnectorAuthType::OpenBankingAuth {
+ api_key: api_key.clone(),
+ key1: key1.clone(),
+ merchant_data: types::MerchantRecipientData::RecipientId(Secret::new(
+ recipient_id,
+ )),
+ }
+ }
+ _ => auth.clone(),
+ };
+
+ Ok(new_auth)
+ }
+ _ => Ok(auth.clone()),
+ }
+}
+
+fn validate_bank_account_data(data: &types::MerchantAccountData) -> RouterResult<()> {
+ match data {
+ types::MerchantAccountData::Iban { iban, .. } => {
+ if iban.peek().len() > 34 {
+ return Err(errors::ApiErrorResponse::InvalidRequestData {
+ message: "IBAN length must be up to 34 characters".to_string(),
+ }
+ .into());
+ }
+ let pattern = Regex::new(r"^[A-Z0-9]*$")
+ .into_report()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("failed to create regex pattern")?;
+
+ let mut iban = iban.peek().to_string();
+
+ if !pattern.is_match(iban.as_str()) {
+ return Err(errors::ApiErrorResponse::InvalidRequestData {
+ message: "IBAN data must be alphanumeric".to_string(),
+ }
+ .into());
+ }
+
+ // MOD check
+ let first_4 = iban.chars().take(4).collect::<String>();
+ iban.push_str(first_4.as_str());
+ let len = iban.len();
+
+ let rearranged_iban = iban
+ .chars()
+ .rev()
+ .take(len - 4)
+ .collect::<String>()
+ .chars()
+ .rev()
+ .collect::<String>();
+
+ let mut result = String::new();
+
+ for c in rearranged_iban.chars() {
+ match c {
+ 'A'..='Z' => {
+ let digit = (c as u8 - b'A') + 10;
+ result.push_str(&format!("{:02}", digit));
+ }
+ _ => result.push(c),
+ }
+ }
+
+ let num = result
+ .parse::<u128>()
+ .into_report()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("failed to validate IBAN")?;
+
+ if num % 97 != 1 {
+ return Err(errors::ApiErrorResponse::InvalidRequestData {
+ message: "Invalid IBAN".to_string(),
+ }
+ .into());
+ }
+
+ Ok(())
+ }
+ types::MerchantAccountData::Bacs {
+ account_number,
+ sort_code,
+ ..
+ } => {
+ if account_number.peek().len() > 8 || sort_code.peek().len() != 6 {
+ return Err(errors::ApiErrorResponse::InvalidRequestData {
+ message: "Invalid BACS numbers".to_string(),
+ }
+ .into());
+ }
+
+ Ok(())
+ }
+ }
+}
+
+async fn connector_recipient_create_call(
+ state: &AppState,
+ merchant_id: &str,
+ connector_name: String,
+ auth: &types::ConnectorAuthType,
+ data: &types::MerchantAccountData,
+) -> RouterResult<String> {
+ let connector = pm_auth_types::api::PaymentAuthConnectorData::get_connector_by_name(
+ connector_name.as_str(),
+ )?;
+
+ let auth = pm_auth_types::ConnectorAuthType::foreign_try_from(auth.clone())
+ .into_report()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed while converting ConnectorAuthType")?;
+
+ let connector_integration: pm_auth_types::api::BoxedConnectorIntegration<
+ '_,
+ pm_auth_types::api::auth_service::RecipientCreate,
+ pm_auth_types::RecipientCreateRequest,
+ pm_auth_types::RecipientCreateResponse,
+ > = connector.connector.get_connector_integration();
+
+ let req = match data {
+ types::MerchantAccountData::Iban { iban, name } => pm_auth_types::RecipientCreateRequest {
+ name: name.clone(),
+ account_data: pm_auth_types::RecipientAccountData::Iban(iban.clone()),
+ address: None,
+ },
+ types::MerchantAccountData::Bacs {
+ account_number,
+ sort_code,
+ name,
+ } => pm_auth_types::RecipientCreateRequest {
+ name: name.clone(),
+ account_data: pm_auth_types::RecipientAccountData::Bacs {
+ sort_code: sort_code.clone(),
+ account_number: account_number.clone(),
+ },
+ address: None,
+ },
+ };
+
+ let router_data = pm_auth_types::RecipientCreateRouterData {
+ flow: std::marker::PhantomData,
+ merchant_id: Some(merchant_id.to_owned()),
+ connector: Some(connector_name),
+ request: req,
+ response: Ok(pm_auth_types::RecipientCreateResponse {
+ recipient_id: "".to_string(),
+ }),
+ connector_http_status_code: None,
+ connector_auth_type: auth,
+ };
+
+ let resp = payment_initiation_service::execute_connector_processing_step(
+ state,
+ connector_integration,
+ &router_data,
+ &connector.connector_name,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed while calling recipient create connector api")?;
+
+ let recipient_create_resp =
+ resp.response
+ .map_err(|err| errors::ApiErrorResponse::ExternalConnectorError {
+ code: err.code,
+ message: err.message,
+ connector: connector.connector_name.to_string(),
+ status_code: err.status_code,
+ reason: err.reason,
+ })?;
+
+ let recipient_id = recipient_create_resp.recipient_id;
+
+ Ok(recipient_id)
+}
+
+async fn locker_recipient_create_call(
+ state: &AppState,
+ merchant_id: &str,
+ key_store: &domain::MerchantKeyStore,
+ data: &types::MerchantAccountData,
+) -> RouterResult<String> {
+ let key = key_store.key.get_inner().peek();
+
+ let enc_data = async {
+ serde_json::to_value(data.to_owned())
+ .map_err(|err| {
+ crate::logger::error!("Error while encoding merchant bank account data: {}", err);
+ errors::VaultError::SavePaymentMethodFailed
+ })
+ .into_report()
+ .change_context(errors::VaultError::SavePaymentMethodFailed)
+ .attach_printable("Unable to encode merchant bank account data")
+ .ok()
+ .map(|v| {
+ let secret: Secret<String> = Secret::new(v.to_string());
+ secret
+ })
+ .async_lift(|inner| domain_types::encrypt_optional(inner, key))
+ .await
+ }
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to encrypt merchant bank account data")?
+ .map(encryption::Encryption::from)
+ .map(|e| e.into_inner())
+ .map_or(Err(errors::ApiErrorResponse::InternalServerError), |e| {
+ Ok(hex::encode(e.peek()))
+ })?;
+
+ let payload = transformers::StoreLockerReq::LockerGeneric(transformers::StoreGenericReq {
+ merchant_id,
+ merchant_customer_id: merchant_id.to_string(),
+ enc_data,
+ });
+
+ let store_resp = cards::call_to_locker_hs(
+ state,
+ &payload,
+ merchant_id,
+ api_enums::LockerChoice::HyperswitchCardVault,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to encrypt merchant bank account data")?;
+
+ Ok(store_resp.card_reference)
+}
diff --git a/crates/router/src/core/fraud_check.rs b/crates/router/src/core/fraud_check.rs
index 0e3f67c051b..bdf34f095e7 100644
--- a/crates/router/src/core/fraud_check.rs
+++ b/crates/router/src/core/fraud_check.rs
@@ -90,6 +90,7 @@ where
key_store,
customer,
&merchant_connector_account,
+ None,
)
.await?;
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 8b3eed45f9e..3b904e3dd1a 100644
--- a/crates/router/src/core/fraud_check/flows/checkout_flow.rs
+++ b/crates/router/src/core/fraud_check/flows/checkout_flow.rs
@@ -17,7 +17,7 @@ use crate::{
domain,
fraud_check::{FraudCheckCheckoutData, FraudCheckResponseData, FrmCheckoutRouterData},
storage::enums as storage_enums,
- BrowserInformation, ConnectorAuthType, ResponseId, RouterData,
+ BrowserInformation, ConnectorAuthType, MerchantRecipientData, ResponseId, RouterData,
},
AppState,
};
@@ -34,6 +34,7 @@ impl ConstructFlowSpecificData<frm_api::Checkout, FraudCheckCheckoutData, FraudC
_key_store: &domain::MerchantKeyStore,
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
+ _merchant_recipient_data: Option<MerchantRecipientData>,
) -> RouterResult<RouterData<frm_api::Checkout, FraudCheckCheckoutData, FraudCheckResponseData>>
{
let status = storage_enums::AttemptStatus::Pending;
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 2de6aaab7c7..a947c81ca17 100644
--- a/crates/router/src/core/fraud_check/flows/record_return.rs
+++ b/crates/router/src/core/fraud_check/flows/record_return.rs
@@ -17,7 +17,7 @@ use crate::{
FraudCheckRecordReturnData, FraudCheckResponseData, FrmRecordReturnRouterData,
},
storage::enums as storage_enums,
- ConnectorAuthType, ResponseId, RouterData,
+ ConnectorAuthType, MerchantRecipientData, ResponseId, RouterData,
},
utils, AppState,
};
@@ -34,6 +34,7 @@ impl ConstructFlowSpecificData<RecordReturn, FraudCheckRecordReturnData, FraudCh
_key_store: &domain::MerchantKeyStore,
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
+ _merchant_recipient_data: Option<MerchantRecipientData>,
) -> RouterResult<RouterData<RecordReturn, FraudCheckRecordReturnData, FraudCheckResponseData>>
{
let status = storage_enums::AttemptStatus::Pending;
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 dfe70570047..b9a7cb87e98 100644
--- a/crates/router/src/core/fraud_check/flows/sale_flow.rs
+++ b/crates/router/src/core/fraud_check/flows/sale_flow.rs
@@ -14,7 +14,7 @@ use crate::{
domain,
fraud_check::{FraudCheckResponseData, FraudCheckSaleData, FrmSaleRouterData},
storage::enums as storage_enums,
- ConnectorAuthType, ResponseId, RouterData,
+ ConnectorAuthType, MerchantRecipientData, ResponseId, RouterData,
},
AppState,
};
@@ -31,6 +31,7 @@ impl ConstructFlowSpecificData<frm_api::Sale, FraudCheckSaleData, FraudCheckResp
_key_store: &domain::MerchantKeyStore,
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
+ _merchant_recipient_data: Option<MerchantRecipientData>,
) -> RouterResult<RouterData<frm_api::Sale, FraudCheckSaleData, FraudCheckResponseData>> {
let status = storage_enums::AttemptStatus::Pending;
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 a84d9a771b4..f9aed084663 100644
--- a/crates/router/src/core/fraud_check/flows/transaction_flow.rs
+++ b/crates/router/src/core/fraud_check/flows/transaction_flow.rs
@@ -16,7 +16,7 @@ use crate::{
FraudCheckResponseData, FraudCheckTransactionData, FrmTransactionRouterData,
},
storage::enums as storage_enums,
- ConnectorAuthType, ResponseId, RouterData,
+ ConnectorAuthType, MerchantRecipientData, ResponseId, RouterData,
},
AppState,
};
@@ -37,6 +37,7 @@ impl
_key_store: &domain::MerchantKeyStore,
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
+ _merchant_recipient_data: Option<MerchantRecipientData>,
) -> RouterResult<
RouterData<frm_api::Transaction, FraudCheckTransactionData, FraudCheckResponseData>,
> {
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 52240bbf39b..f8aa2608261 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -14,13 +14,17 @@ pub mod types;
use std::{fmt::Debug, marker::PhantomData, ops::Deref, time::Instant, vec::IntoIter};
use api_models::{self, enums, payments::HeaderPayload};
-use common_utils::{ext_traits::AsyncExt, pii, types::Surcharge};
+use common_utils::{
+ ext_traits::{AsyncExt, StringExt},
+ pii,
+ types::Surcharge,
+};
use data_models::mandates::{CustomerAcceptance, MandateData};
use diesel_models::{ephemeral_key, fraud_check::FraudCheck};
use error_stack::{IntoReport, ResultExt};
use futures::future::join_all;
use helpers::ApplePayData;
-use masking::Secret;
+use masking::{PeekInterface, Secret};
use redis_interface::errors::RedisError;
use router_env::{instrument, tracing};
#[cfg(feature = "olap")]
@@ -51,7 +55,7 @@ use crate::{
core::{
authentication as authentication_core,
errors::{self, CustomResult, RouterResponse, RouterResult},
- payment_methods::PaymentMethodRetrieve,
+ payment_methods::{self, PaymentMethodRetrieve},
utils,
},
db::StorageInterface,
@@ -176,6 +180,10 @@ where
)
.await?;
+ let op_ref = &operation;
+ let should_trigger_post_processing_flows =
+ matches!(format!("{op_ref:?}").as_str(), "PaymentConfirm");
+
let mut connector_http_status_code = None;
let mut external_latency = None;
if let Some(connector_details) = connector {
@@ -243,11 +251,11 @@ where
} else {
None
};
- let router_data = call_connector_service(
+ let (router_data, mca) = call_connector_service(
state,
&merchant_account,
&key_store,
- connector,
+ connector.clone(),
&operation,
&mut payment_data,
&customer,
@@ -267,7 +275,7 @@ where
external_latency = router_data.external_latency;
//add connector http status code metrics
add_connector_http_status_code_metrics(connector_http_status_code);
- operation
+ payment_data = operation
.to_post_update_tracker()?
.update_tracker(
state,
@@ -276,7 +284,23 @@ where
router_data,
merchant_account.storage_scheme,
)
- .await?
+ .await?;
+
+ if should_trigger_post_processing_flows {
+ complete_postprocessing_steps_if_required(
+ state,
+ &merchant_account,
+ &key_store,
+ &customer,
+ &mca,
+ &connector,
+ &mut payment_data,
+ op_ref,
+ )
+ .await?;
+ }
+
+ payment_data
}
api::ConnectorCallType::Retryable(connectors) => {
@@ -298,7 +322,7 @@ where
} else {
None
};
- let router_data = call_connector_service(
+ let (router_data, mca) = call_connector_service(
state,
&merchant_account,
&key_store,
@@ -333,7 +357,7 @@ where
state,
&mut payment_data,
connectors,
- connector_data,
+ connector_data.clone(),
router_data,
&merchant_account,
&key_store,
@@ -355,7 +379,7 @@ where
external_latency = router_data.external_latency;
//add connector http status code metrics
add_connector_http_status_code_metrics(connector_http_status_code);
- operation
+ payment_data = operation
.to_post_update_tracker()?
.update_tracker(
state,
@@ -364,7 +388,23 @@ where
router_data,
merchant_account.storage_scheme,
)
- .await?
+ .await?;
+
+ if should_trigger_post_processing_flows {
+ complete_postprocessing_steps_if_required(
+ state,
+ &merchant_account,
+ &key_store,
+ &customer,
+ &mca,
+ &connector_data,
+ &mut payment_data,
+ op_ref,
+ )
+ .await?;
+ }
+
+ payment_data
}
api::ConnectorCallType::SessionMultiple(connectors) => {
@@ -669,7 +709,7 @@ pub async fn payments_core<F, Res, Req, Op, FData, Ctx>(
) -> RouterResponse<Res>
where
F: Send + Clone + Sync,
- FData: Send + Sync,
+ FData: Send + Sync + Clone,
Op: Operation<F, Req, Ctx> + Send + Sync + Clone,
Req: Debug + Authenticate + Clone,
Res: transformers::ToResponse<Req, PaymentData<F>, Op>,
@@ -1026,7 +1066,10 @@ pub async fn call_connector_service<F, RouterDReq, ApiRequest, Ctx>(
schedule_time: Option<time::PrimitiveDateTime>,
header_payload: HeaderPayload,
frm_suggestion: Option<storage_enums::FrmSuggestion>,
-) -> RouterResult<router_types::RouterData<F, RouterDReq, router_types::PaymentsResponseData>>
+) -> RouterResult<(
+ router_types::RouterData<F, RouterDReq, router_types::PaymentsResponseData>,
+ helpers::MerchantConnectorAccountType,
+)>
where
F: Send + Clone + Sync,
RouterDReq: Send + Sync,
@@ -1089,6 +1132,15 @@ where
)
.await?;
+ let merchant_recipient_data = get_merchant_bank_data_for_open_banking_connectors(
+ &merchant_connector_account,
+ key_store,
+ &connector,
+ state,
+ merchant_account,
+ )
+ .await?;
+
let mut router_data = payment_data
.construct_router_data(
state,
@@ -1097,6 +1149,7 @@ where
key_store,
customer,
&merchant_connector_account,
+ merchant_recipient_data,
)
.await?;
@@ -1165,7 +1218,9 @@ where
..
}) = router_data.response.to_owned()
{
- payment_data.sessions_token.push(session_token);
+ payment_data
+ .sessions_token
+ .push(api::SessionTokenType::Wallet(session_token));
};
// In case of authorize flow, pre-task and post-tasks are being called in build request
@@ -1210,7 +1265,7 @@ where
)
.await?;
- let router_data_res = if should_continue_further {
+ let router_data = if should_continue_further {
// The status of payment_attempt and intent will be updated in the previous step
// update this in router_data.
// This is added because few connector integrations do not update the status,
@@ -1229,13 +1284,63 @@ where
.await
} else {
Ok(router_data)
- };
+ }?;
let etime_connector = Instant::now();
let duration_connector = etime_connector.saturating_duration_since(stime_connector);
tracing::info!(duration = format!("Duration taken: {}", duration_connector.as_millis()));
- router_data_res
+ Ok((router_data, merchant_connector_account))
+}
+
+async fn get_merchant_bank_data_for_open_banking_connectors(
+ merchant_connector_account: &helpers::MerchantConnectorAccountType,
+ key_store: &domain::MerchantKeyStore,
+ connector: &api::ConnectorData,
+ state: &AppState,
+ merchant_account: &domain::MerchantAccount,
+) -> RouterResult<Option<router_types::MerchantRecipientData>> {
+ let auth_type: router_types::ConnectorAuthType = merchant_connector_account
+ .get_connector_account_details()
+ .parse_value("ConnectorAuthType")
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed while parsing value for ConnectorAuthType")?;
+ let connector_name = enums::Connector::to_string(&connector.connector_name);
+ let locker_based_connector_list = state.conf.locker_open_banking_connectors.clone();
+ let contains = locker_based_connector_list
+ .connector_list
+ .get(connector_name.as_str());
+ let recipient_id = helpers::get_recipient_id_from_open_banking_auth(&auth_type)?;
+ let final_recipient_data = if let Some(id) = recipient_id {
+ if let Some(_con) = contains {
+ let resp = payment_methods::cards::get_payment_method_from_hs_locker(
+ state,
+ key_store,
+ merchant_account.merchant_id.as_str(),
+ merchant_account.merchant_id.as_str(),
+ id.as_str(),
+ Some(enums::LockerChoice::HyperswitchCardVault),
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Merchant bank account data could not be fetched from locker")?;
+
+ let parsed: router_types::MerchantAccountData = resp
+ .peek()
+ .to_string()
+ .parse_struct("MerchantAccountData")
+ .change_context(errors::ApiErrorResponse::InternalServerError)?;
+
+ Some(router_types::MerchantRecipientData::AccountData(parsed))
+ } else {
+ Some(router_types::MerchantRecipientData::RecipientId(
+ Secret::new(id),
+ ))
+ }
+ } else {
+ None
+ };
+ Ok(final_recipient_data)
}
async fn blocklist_guard<F, ApiRequest, Ctx>(
@@ -1342,6 +1447,7 @@ where
key_store,
customer,
&merchant_connector_account,
+ None,
)
.await?;
@@ -1375,7 +1481,9 @@ where
session_token,
api_models::payments::SessionToken::NoSessionTokenReceived,
) {
- payment_data.sessions_token.push(session_token);
+ payment_data
+ .sessions_token
+ .push(api::SessionTokenType::Wallet(session_token));
}
}
}
@@ -1472,6 +1580,7 @@ where
key_store,
customer,
merchant_connector_account,
+ None,
)
.await?;
@@ -1603,6 +1712,17 @@ where
(router_data, should_continue_payment)
}
}
+ Some(api_models::payments::PaymentMethodData::BankRedirect(data)) => match data {
+ api_models::payments::BankRedirectData::OpenBanking { .. } => {
+ if connector.connector_name == router_types::Connector::Plaid {
+ router_data = router_data.preprocessing_steps(state, connector).await?;
+ (router_data, true)
+ } else {
+ (router_data, should_continue_payment)
+ }
+ }
+ _ => (router_data, should_continue_payment),
+ },
_ => {
// 3DS validation for paypal cards after verification (authorize call)
if connector.connector_name == router_types::Connector::Paypal
@@ -1623,6 +1743,71 @@ where
Ok(router_data_and_should_continue_payment)
}
+#[allow(clippy::too_many_arguments)]
+async fn complete_postprocessing_steps_if_required<F, Q, Ctx, RouterDReq>(
+ state: &AppState,
+ merchant_account: &domain::MerchantAccount,
+ key_store: &domain::MerchantKeyStore,
+ customer: &Option<domain::Customer>,
+ merchant_conn_account: &helpers::MerchantConnectorAccountType,
+ connector: &api::ConnectorData,
+ payment_data: &mut PaymentData<F>,
+ _operation: &BoxedOperation<'_, F, Q, Ctx>,
+) -> RouterResult<router_types::RouterData<F, RouterDReq, router_types::PaymentsResponseData>>
+where
+ F: Send + Clone + Sync,
+ RouterDReq: Send + Sync,
+
+ router_types::RouterData<F, RouterDReq, router_types::PaymentsResponseData>:
+ Feature<F, RouterDReq> + Send,
+ dyn api::Connector:
+ services::api::ConnectorIntegration<F, RouterDReq, router_types::PaymentsResponseData>,
+ PaymentData<F>: ConstructFlowSpecificData<F, RouterDReq, router_types::PaymentsResponseData>,
+{
+ let mut router_data = payment_data
+ .construct_router_data(
+ state,
+ connector.connector.id(),
+ merchant_account,
+ key_store,
+ customer,
+ merchant_conn_account,
+ None,
+ )
+ .await?;
+
+ match payment_data.payment_method_data.clone() {
+ Some(api_models::payments::PaymentMethodData::BankRedirect(data)) => match data {
+ api_models::payments::BankRedirectData::OpenBanking { .. } => {
+ if connector.connector_name == router_types::Connector::Plaid {
+ router_data = router_data.postprocessing_steps(state, connector).await?;
+ let token = if let Ok(ref res) = router_data.response {
+ match res {
+ router_types::PaymentsResponseData::PostProcessingResponse {
+ session_token,
+ } => session_token
+ .as_ref()
+ .map(|token| api::SessionTokenType::OpenBanking(token.clone())),
+ _ => None,
+ }
+ } else {
+ None
+ };
+ if let Some(t) = token {
+ payment_data.sessions_token.push(t);
+ }
+
+ Ok(router_data)
+ } else {
+ Ok(router_data)
+ }
+ }
+ _ => Ok(router_data),
+ },
+ _ => Ok(router_data),
+ }
+}
+
pub fn is_preprocessing_required_for_wallets(connector_name: String) -> bool {
connector_name == *"trustpay" || connector_name == *"payme"
}
@@ -2062,7 +2247,7 @@ where
pub refunds: Vec<storage::Refund>,
pub disputes: Vec<storage::Dispute>,
pub attempts: Option<Vec<storage::PaymentAttempt>>,
- pub sessions_token: Vec<api::SessionToken>,
+ pub sessions_token: Vec<api::SessionTokenType>,
pub card_cvc: Option<Secret<String>>,
pub email: Option<pii::Email>,
pub creds_identifier: Option<String>,
diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs
index fe4a504861d..bdca658a89f 100644
--- a/crates/router/src/core/payments/flows.rs
+++ b/crates/router/src/core/payments/flows.rs
@@ -25,6 +25,7 @@ use crate::{
};
#[async_trait]
+#[allow(clippy::too_many_arguments)]
pub trait ConstructFlowSpecificData<F, Req, Res> {
async fn construct_router_data<'a>(
&self,
@@ -34,6 +35,7 @@ pub trait ConstructFlowSpecificData<F, Req, Res> {
key_store: &domain::MerchantKeyStore,
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
+ merchant_recipient_data: Option<types::MerchantRecipientData>,
) -> RouterResult<types::RouterData<F, Req, Res>>;
}
@@ -93,6 +95,19 @@ pub trait Feature<F, T> {
Ok(self)
}
+ async fn postprocessing_steps<'a>(
+ self,
+ _state: &AppState,
+ _connector: &api::ConnectorData,
+ ) -> RouterResult<Self>
+ where
+ F: Clone,
+ Self: Sized,
+ dyn api::Connector: services::ConnectorIntegration<F, T, types::PaymentsResponseData>,
+ {
+ Ok(self)
+ }
+
async fn create_connector_customer<'a>(
&self,
_state: &AppState,
@@ -146,6 +161,7 @@ impl<const T: u8>
default_imp_for_complete_authorize!(
connector::Threedsecureio,
+ connector::Plaid,
connector::Aci,
connector::Adyen,
connector::Bitpay,
@@ -295,6 +311,7 @@ impl<const T: u8>
default_imp_for_create_customer!(
connector::Threedsecureio,
+ connector::Plaid,
connector::Aci,
connector::Adyen,
connector::Airwallex,
@@ -378,6 +395,7 @@ impl<const T: u8> services::ConnectorRedirectResponse for connector::DummyConnec
default_imp_for_connector_redirect_response!(
connector::Threedsecureio,
+ connector::Plaid,
connector::Aci,
connector::Adyen,
connector::Bitpay,
@@ -430,6 +448,7 @@ impl<const T: u8> api::ConnectorTransactionId for connector::DummyConnector<T> {
default_imp_for_connector_request_id!(
connector::Threedsecureio,
+ connector::Plaid,
connector::Aci,
connector::Adyen,
connector::Airwallex,
@@ -515,6 +534,7 @@ impl<const T: u8>
default_imp_for_accept_dispute!(
connector::Threedsecureio,
+ connector::Plaid,
connector::Aci,
connector::Adyen,
connector::Airwallex,
@@ -620,6 +640,7 @@ impl<const T: u8>
default_imp_for_file_upload!(
connector::Threedsecureio,
+ connector::Plaid,
connector::Aci,
connector::Adyen,
connector::Airwallex,
@@ -702,6 +723,7 @@ impl<const T: u8>
default_imp_for_submit_evidence!(
connector::Threedsecureio,
+ connector::Plaid,
connector::Aci,
connector::Adyen,
connector::Airwallex,
@@ -784,6 +806,7 @@ impl<const T: u8>
default_imp_for_defend_dispute!(
connector::Threedsecureio,
+ connector::Plaid,
connector::Aci,
connector::Adyen,
connector::Airwallex,
@@ -853,6 +876,21 @@ macro_rules! default_imp_for_pre_processing_steps{
};
}
+macro_rules! default_imp_for_post_processing_steps{
+ ($($path:ident::$connector:ident),*)=> {
+ $(
+ impl api::PaymentsPostProcessing for $path::$connector {}
+ impl
+ services::ConnectorIntegration<
+ api::PostProcessing,
+ types::PaymentsPostProcessingData,
+ types::PaymentsResponseData,
+ > for $path::$connector
+ {}
+ )*
+ };
+}
+
#[cfg(feature = "dummy_connector")]
impl<const T: u8> api::PaymentsPreProcessing for connector::DummyConnector<T> {}
#[cfg(feature = "dummy_connector")]
@@ -867,6 +905,7 @@ impl<const T: u8>
default_imp_for_pre_processing_steps!(
connector::Threedsecureio,
+ connector::Plaid,
connector::Aci,
connector::Airwallex,
connector::Authorizedotnet,
@@ -913,6 +952,75 @@ default_imp_for_pre_processing_steps!(
connector::Zen
);
+#[cfg(feature = "dummy_connector")]
+impl<const T: u8> api::PaymentsPostProcessing for connector::DummyConnector<T> {}
+#[cfg(feature = "dummy_connector")]
+impl<const T: u8>
+ services::ConnectorIntegration<
+ api::PostProcessing,
+ types::PaymentsPostProcessingData,
+ types::PaymentsResponseData,
+ > for connector::DummyConnector<T>
+{
+}
+
+default_imp_for_post_processing_steps!(
+ connector::Aci,
+ connector::Airwallex,
+ connector::Authorizedotnet,
+ connector::Bambora,
+ connector::Bitpay,
+ connector::Bluesnap,
+ connector::Boku,
+ connector::Braintree,
+ connector::Cashtocode,
+ connector::Checkout,
+ connector::Coinbase,
+ connector::Cryptopay,
+ connector::Dlocal,
+ connector::Iatapay,
+ connector::Fiserv,
+ connector::Forte,
+ connector::Globalpay,
+ connector::Globepay,
+ connector::Helcim,
+ connector::Klarna,
+ connector::Mollie,
+ connector::Multisafepay,
+ connector::Nexinets,
+ connector::Noon,
+ connector::Nuvei,
+ connector::Opayo,
+ connector::Opennode,
+ connector::Payeezy,
+ connector::Payu,
+ connector::Placetopay,
+ connector::Powertranz,
+ connector::Prophetpay,
+ connector::Rapyd,
+ connector::Riskified,
+ connector::Shift4,
+ connector::Signifyd,
+ connector::Square,
+ connector::Stax,
+ connector::Tsys,
+ connector::Volt,
+ connector::Wise,
+ connector::Worldline,
+ connector::Worldpay,
+ connector::Zen,
+ connector::Adyen,
+ connector::Bankofamerica,
+ connector::Cybersource,
+ connector::Gocardless,
+ connector::Nmi,
+ connector::Payme,
+ connector::Paypal,
+ connector::Stripe,
+ connector::Trustpay,
+ connector::Threedsecureio
+);
+
macro_rules! default_imp_for_payouts {
($($path:ident::$connector:ident),*) => {
$(
@@ -926,6 +1034,7 @@ impl<const T: u8> api::Payouts for connector::DummyConnector<T> {}
default_imp_for_payouts!(
connector::Threedsecureio,
+ connector::Plaid,
connector::Aci,
connector::Airwallex,
connector::Authorizedotnet,
@@ -1009,6 +1118,7 @@ impl<const T: u8>
#[cfg(feature = "payouts")]
default_imp_for_payouts_create!(
connector::Threedsecureio,
+ connector::Plaid,
connector::Aci,
connector::Airwallex,
connector::Authorizedotnet,
@@ -1095,6 +1205,7 @@ impl<const T: u8>
#[cfg(feature = "payouts")]
default_imp_for_payouts_eligibility!(
connector::Threedsecureio,
+ connector::Plaid,
connector::Aci,
connector::Airwallex,
connector::Authorizedotnet,
@@ -1178,6 +1289,7 @@ impl<const T: u8>
#[cfg(feature = "payouts")]
default_imp_for_payouts_fulfill!(
connector::Threedsecureio,
+ connector::Plaid,
connector::Aci,
connector::Airwallex,
connector::Authorizedotnet,
@@ -1261,6 +1373,7 @@ impl<const T: u8>
#[cfg(feature = "payouts")]
default_imp_for_payouts_cancel!(
connector::Threedsecureio,
+ connector::Plaid,
connector::Aci,
connector::Airwallex,
connector::Authorizedotnet,
@@ -1344,6 +1457,7 @@ impl<const T: u8>
#[cfg(feature = "payouts")]
default_imp_for_payouts_quote!(
connector::Threedsecureio,
+ connector::Plaid,
connector::Aci,
connector::Adyen,
connector::Airwallex,
@@ -1428,6 +1542,7 @@ impl<const T: u8>
#[cfg(feature = "payouts")]
default_imp_for_payouts_recipient!(
connector::Threedsecureio,
+ connector::Plaid,
connector::Aci,
connector::Adyen,
connector::Airwallex,
@@ -1511,6 +1626,7 @@ impl<const T: u8>
default_imp_for_approve!(
connector::Threedsecureio,
+ connector::Plaid,
connector::Aci,
connector::Adyen,
connector::Airwallex,
@@ -1595,6 +1711,7 @@ impl<const T: u8>
default_imp_for_reject!(
connector::Threedsecureio,
+ connector::Plaid,
connector::Aci,
connector::Adyen,
connector::Airwallex,
@@ -1663,6 +1780,7 @@ impl<const T: u8> api::FraudCheck for connector::DummyConnector<T> {}
default_imp_for_fraud_check!(
connector::Threedsecureio,
+ connector::Plaid,
connector::Aci,
connector::Adyen,
connector::Airwallex,
@@ -1747,6 +1865,7 @@ impl<const T: u8>
#[cfg(feature = "frm")]
default_imp_for_frm_sale!(
connector::Threedsecureio,
+ connector::Plaid,
connector::Aci,
connector::Adyen,
connector::Airwallex,
@@ -1831,6 +1950,7 @@ impl<const T: u8>
#[cfg(feature = "frm")]
default_imp_for_frm_checkout!(
connector::Threedsecureio,
+ connector::Plaid,
connector::Aci,
connector::Adyen,
connector::Airwallex,
@@ -1915,6 +2035,7 @@ impl<const T: u8>
#[cfg(feature = "frm")]
default_imp_for_frm_transaction!(
connector::Threedsecureio,
+ connector::Plaid,
connector::Aci,
connector::Adyen,
connector::Airwallex,
@@ -1999,6 +2120,7 @@ impl<const T: u8>
#[cfg(feature = "frm")]
default_imp_for_frm_fulfillment!(
connector::Threedsecureio,
+ connector::Plaid,
connector::Aci,
connector::Adyen,
connector::Airwallex,
@@ -2083,6 +2205,7 @@ impl<const T: u8>
#[cfg(feature = "frm")]
default_imp_for_frm_record_return!(
connector::Threedsecureio,
+ connector::Plaid,
connector::Aci,
connector::Adyen,
connector::Airwallex,
@@ -2165,6 +2288,7 @@ impl<const T: u8>
default_imp_for_incremental_authorization!(
connector::Threedsecureio,
+ connector::Plaid,
connector::Aci,
connector::Adyen,
connector::Airwallex,
@@ -2246,6 +2370,7 @@ impl<const T: u8>
}
default_imp_for_revoking_mandates!(
connector::Threedsecureio,
+ connector::Plaid,
connector::Aci,
connector::Adyen,
connector::Airwallex,
@@ -2419,5 +2544,6 @@ default_imp_for_connector_authentication!(
connector::Wise,
connector::Worldline,
connector::Worldpay,
- connector::Zen
+ connector::Zen,
+ connector::Plaid
);
diff --git a/crates/router/src/core/payments/flows/approve_flow.rs b/crates/router/src/core/payments/flows/approve_flow.rs
index 14b710de914..43f2f3877ce 100644
--- a/crates/router/src/core/payments/flows/approve_flow.rs
+++ b/crates/router/src/core/payments/flows/approve_flow.rs
@@ -24,6 +24,7 @@ impl
key_store: &domain::MerchantKeyStore,
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
+ merchant_recipient_data: Option<types::MerchantRecipientData>,
) -> RouterResult<types::PaymentsApproveRouterData> {
Box::pin(transformers::construct_payment_router_data::<
api::Approve,
@@ -36,6 +37,7 @@ impl
key_store,
customer,
merchant_connector_account,
+ merchant_recipient_data,
))
.await
}
diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs
index cc2540aa221..489b3b87eaa 100644
--- a/crates/router/src/core/payments/flows/authorize_flow.rs
+++ b/crates/router/src/core/payments/flows/authorize_flow.rs
@@ -32,6 +32,7 @@ impl
key_store: &domain::MerchantKeyStore,
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
+ merchant_recipient_data: Option<types::MerchantRecipientData>,
) -> RouterResult<
types::RouterData<
api::Authorize,
@@ -50,6 +51,7 @@ impl
key_store,
customer,
merchant_connector_account,
+ merchant_recipient_data,
))
.await
}
@@ -179,6 +181,14 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu
authorize_preprocessing_steps(state, &self, true, connector).await
}
+ async fn postprocessing_steps<'a>(
+ self,
+ state: &AppState,
+ connector: &api::ConnectorData,
+ ) -> RouterResult<Self> {
+ authorize_postprocessing_steps(state, &self, true, connector).await
+ }
+
async fn create_connector_customer<'a>(
&self,
state: &AppState,
@@ -368,6 +378,58 @@ pub async fn authorize_preprocessing_steps<F: Clone>(
}
}
+pub async fn authorize_postprocessing_steps<F: Clone>(
+ state: &AppState,
+ router_data: &types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>,
+ confirm: bool,
+ connector: &api::ConnectorData,
+) -> RouterResult<types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>> {
+ if confirm {
+ let connector_integration: services::BoxedConnectorIntegration<
+ '_,
+ api::PostProcessing,
+ types::PaymentsPostProcessingData,
+ types::PaymentsResponseData,
+ > = connector.connector.get_connector_integration();
+
+ let postprocessing_request_data =
+ types::PaymentsPostProcessingData::try_from(router_data.request.to_owned())?;
+
+ let postprocessing_response_data: Result<
+ types::PaymentsResponseData,
+ types::ErrorResponse,
+ > = Err(types::ErrorResponse::default());
+
+ let postprocessing_router_data =
+ payments::helpers::router_data_type_conversion::<_, api::PostProcessing, _, _, _, _>(
+ router_data.clone(),
+ postprocessing_request_data,
+ postprocessing_response_data,
+ );
+
+ let resp = services::execute_connector_processing_step(
+ state,
+ connector_integration,
+ &postprocessing_router_data,
+ payments::CallConnectorAction::Trigger,
+ None,
+ )
+ .await
+ .to_payment_failed_response()?;
+
+ let authorize_router_data =
+ payments::helpers::router_data_type_conversion::<_, F, _, _, _, _>(
+ resp.clone(),
+ router_data.request.to_owned(),
+ resp.response,
+ );
+
+ Ok(authorize_router_data)
+ } else {
+ Ok(router_data.clone())
+ }
+}
+
impl<F> TryFrom<&types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>>
for types::ConnectorCustomerData
{
@@ -424,6 +486,29 @@ impl TryFrom<types::PaymentsAuthorizeData> for types::PaymentsPreProcessingData
}
}
+impl TryFrom<types::PaymentsAuthorizeData> for types::PaymentsPostProcessingData {
+ type Error = error_stack::Report<errors::ApiErrorResponse>;
+
+ fn try_from(data: types::PaymentsAuthorizeData) -> Result<Self, Self::Error> {
+ Ok(Self {
+ payment_method_data: data.payment_method_data,
+ amount: data.amount,
+ email: data.email,
+ currency: data.currency,
+ payment_method_type: data.payment_method_type,
+ setup_mandate_details: data.setup_mandate_details,
+ capture_method: data.capture_method,
+ order_details: data.order_details,
+ router_return_url: data.router_return_url,
+ webhook_url: data.webhook_url,
+ complete_authorize_url: data.complete_authorize_url,
+ browser_info: data.browser_info,
+ connector_transaction_id: data.related_transaction_id,
+ customer_id: data.customer_id,
+ })
+ }
+}
+
impl TryFrom<types::CompleteAuthorizeData> for types::PaymentsPreProcessingData {
type Error = error_stack::Report<errors::ApiErrorResponse>;
diff --git a/crates/router/src/core/payments/flows/cancel_flow.rs b/crates/router/src/core/payments/flows/cancel_flow.rs
index 5918380ee0b..0a6abda11ef 100644
--- a/crates/router/src/core/payments/flows/cancel_flow.rs
+++ b/crates/router/src/core/payments/flows/cancel_flow.rs
@@ -23,6 +23,7 @@ impl ConstructFlowSpecificData<api::Void, types::PaymentsCancelData, types::Paym
key_store: &domain::MerchantKeyStore,
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
+ merchant_recipient_data: Option<types::MerchantRecipientData>,
) -> RouterResult<types::PaymentsCancelRouterData> {
Box::pin(transformers::construct_payment_router_data::<
api::Void,
@@ -35,6 +36,7 @@ impl ConstructFlowSpecificData<api::Void, types::PaymentsCancelData, types::Paym
key_store,
customer,
merchant_connector_account,
+ merchant_recipient_data,
))
.await
}
diff --git a/crates/router/src/core/payments/flows/capture_flow.rs b/crates/router/src/core/payments/flows/capture_flow.rs
index d2b7c8e91bd..4d14a188922 100644
--- a/crates/router/src/core/payments/flows/capture_flow.rs
+++ b/crates/router/src/core/payments/flows/capture_flow.rs
@@ -24,6 +24,7 @@ impl
key_store: &domain::MerchantKeyStore,
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
+ merchant_recipient_data: Option<types::MerchantRecipientData>,
) -> RouterResult<types::PaymentsCaptureRouterData> {
Box::pin(transformers::construct_payment_router_data::<
api::Capture,
@@ -36,6 +37,7 @@ impl
key_store,
customer,
merchant_connector_account,
+ merchant_recipient_data,
))
.await
}
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 68d0ee8d475..c2c21569703 100644
--- a/crates/router/src/core/payments/flows/complete_authorize_flow.rs
+++ b/crates/router/src/core/payments/flows/complete_authorize_flow.rs
@@ -28,6 +28,7 @@ impl
key_store: &domain::MerchantKeyStore,
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
+ merchant_recipient_data: Option<types::MerchantRecipientData>,
) -> RouterResult<
types::RouterData<
api::CompleteAuthorize,
@@ -46,6 +47,7 @@ impl
key_store,
customer,
merchant_connector_account,
+ merchant_recipient_data,
))
.await
}
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 387916bab7c..6ab6d37a3fb 100644
--- a/crates/router/src/core/payments/flows/incremental_authorization_flow.rs
+++ b/crates/router/src/core/payments/flows/incremental_authorization_flow.rs
@@ -27,6 +27,7 @@ impl
key_store: &domain::MerchantKeyStore,
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
+ merchant_recipient_data: Option<types::MerchantRecipientData>,
) -> RouterResult<types::PaymentsIncrementalAuthorizationRouterData> {
Box::pin(transformers::construct_payment_router_data::<
api::IncrementalAuthorization,
@@ -39,6 +40,7 @@ impl
key_store,
customer,
merchant_connector_account,
+ merchant_recipient_data,
))
.await
}
diff --git a/crates/router/src/core/payments/flows/psync_flow.rs b/crates/router/src/core/payments/flows/psync_flow.rs
index cb7a764985d..1f519f14dfc 100644
--- a/crates/router/src/core/payments/flows/psync_flow.rs
+++ b/crates/router/src/core/payments/flows/psync_flow.rs
@@ -25,6 +25,7 @@ impl ConstructFlowSpecificData<api::PSync, types::PaymentsSyncData, types::Payme
key_store: &domain::MerchantKeyStore,
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
+ merchant_recipient_data: Option<types::MerchantRecipientData>,
) -> RouterResult<
types::RouterData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>,
> {
@@ -39,6 +40,7 @@ impl ConstructFlowSpecificData<api::PSync, types::PaymentsSyncData, types::Payme
key_store,
customer,
merchant_connector_account,
+ merchant_recipient_data,
))
.await
}
diff --git a/crates/router/src/core/payments/flows/reject_flow.rs b/crates/router/src/core/payments/flows/reject_flow.rs
index 910cc955e63..679b7f398bd 100644
--- a/crates/router/src/core/payments/flows/reject_flow.rs
+++ b/crates/router/src/core/payments/flows/reject_flow.rs
@@ -23,6 +23,7 @@ impl ConstructFlowSpecificData<api::Reject, types::PaymentsRejectData, types::Pa
key_store: &domain::MerchantKeyStore,
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
+ merchant_recipient_data: Option<types::MerchantRecipientData>,
) -> RouterResult<types::PaymentsRejectRouterData> {
Box::pin(transformers::construct_payment_router_data::<
api::Reject,
@@ -35,6 +36,7 @@ impl ConstructFlowSpecificData<api::Reject, types::PaymentsRejectData, types::Pa
key_store,
customer,
merchant_connector_account,
+ merchant_recipient_data,
))
.await
}
diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs
index e29b66ea0ca..8a54a2a8b79 100644
--- a/crates/router/src/core/payments/flows/session_flow.rs
+++ b/crates/router/src/core/payments/flows/session_flow.rs
@@ -30,6 +30,7 @@ impl
key_store: &domain::MerchantKeyStore,
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
+ merchant_recipient_data: Option<types::MerchantRecipientData>,
) -> RouterResult<types::PaymentsSessionRouterData> {
Box::pin(transformers::construct_payment_router_data::<
api::Session,
@@ -42,6 +43,7 @@ impl
key_store,
customer,
merchant_connector_account,
+ merchant_recipient_data,
))
.await
}
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 71d43989336..a3757975186 100644
--- a/crates/router/src/core/payments/flows/setup_mandate_flow.rs
+++ b/crates/router/src/core/payments/flows/setup_mandate_flow.rs
@@ -34,6 +34,7 @@ impl
key_store: &domain::MerchantKeyStore,
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
+ merchant_recipient_data: Option<types::MerchantRecipientData>,
) -> RouterResult<types::SetupMandateRouterData> {
Box::pin(transformers::construct_payment_router_data::<
api::SetupMandate,
@@ -46,6 +47,7 @@ impl
key_store,
customer,
merchant_connector_account,
+ merchant_recipient_data,
))
.await
}
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index a60fae4f579..f8917d37c4e 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -49,7 +49,7 @@ use crate::{
},
storage::{self, enums as storage_enums, ephemeral_key, CustomerUpdate::Update},
transformers::{ForeignFrom, ForeignTryFrom},
- ErrorResponse, MandateReference, RouterData,
+ ConnectorAuthType, ErrorResponse, MandateReference, MerchantRecipientData, RouterData,
},
utils::{
self,
@@ -2021,6 +2021,7 @@ pub fn validate_payment_method_type_against_payment_method(
| api_enums::PaymentMethodType::Bizum
| api_enums::PaymentMethodType::Interac
| api_enums::PaymentMethodType::OpenBankingUk
+ | api_enums::PaymentMethodType::OpenBanking
),
api_enums::PaymentMethod::BankTransfer => matches!(
payment_method_type,
@@ -4007,3 +4008,19 @@ pub fn validate_mandate_data_and_future_usage(
Ok(())
}
}
+
+pub fn get_recipient_id_from_open_banking_auth(
+ auth: &ConnectorAuthType,
+) -> Result<Option<String>, errors::ApiErrorResponse> {
+ match auth {
+ ConnectorAuthType::OpenBankingAuth {
+ api_key: _,
+ key1: _,
+ merchant_data,
+ } => match merchant_data {
+ MerchantRecipientData::RecipientId(id) => Ok(Some(id.peek().to_string())),
+ _ => Err(errors::ApiErrorResponse::InternalServerError),
+ },
+ _ => Ok(None),
+ }
+}
diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs
index 33e8ff26edc..eae82e94d32 100644
--- a/crates/router/src/core/payments/operations/payment_response.rs
+++ b/crates/router/src/core/payments/operations/payment_response.rs
@@ -703,6 +703,7 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
types::PaymentsResponseData::IncrementalAuthorizationResponse { .. } => {
(None, None)
}
+ types::PaymentsResponseData::PostProcessingResponse { .. } => (None, None),
types::PaymentsResponseData::MultipleCaptureResponse {
capture_sync_response_list,
} => match payment_data.multiple_capture_data {
diff --git a/crates/router/src/core/payments/retry.rs b/crates/router/src/core/payments/retry.rs
index 91b6061c111..87bb22f454f 100644
--- a/crates/router/src/core/payments/retry.rs
+++ b/crates/router/src/core/payments/retry.rs
@@ -302,7 +302,7 @@ where
)
.await?;
- payments::call_connector_service(
+ let (router_data, _mca) = payments::call_connector_service(
state,
merchant_account,
key_store,
@@ -316,7 +316,9 @@ where
api::HeaderPayload::default(),
frm_suggestion,
)
- .await
+ .await?;
+
+ Ok(router_data)
}
#[instrument(skip_all)]
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index 9dd7df66fa6..8e15e6ba61e 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -29,6 +29,7 @@ use crate::{
};
#[instrument(skip_all)]
+#[allow(clippy::too_many_arguments)]
pub async fn construct_payment_router_data<'a, F, T>(
state: &'a AppState,
payment_data: PaymentData<F>,
@@ -37,6 +38,7 @@ pub async fn construct_payment_router_data<'a, F, T>(
_key_store: &domain::MerchantKeyStore,
customer: &'a Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
+ merchant_recipient_data: Option<types::MerchantRecipientData>,
) -> RouterResult<types::RouterData<F, T, types::PaymentsResponseData>>
where
T: TryFrom<PaymentAdditionalData<'a, F>>,
@@ -141,7 +143,15 @@ where
.payment_attempt
.authentication_type
.unwrap_or_default(),
- connector_meta_data: merchant_connector_account.get_metadata(),
+ connector_meta_data: if let Some(data) = merchant_recipient_data {
+ let val = serde_json::to_value(data)
+ .into_report()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed while encoding MerchantRecipientDatas")?;
+ Some(masking::Secret::new(val))
+ } else {
+ merchant_connector_account.get_metadata()
+ },
request: T::try_from(additional_data)?,
response,
amount_captured: payment_data.payment_intent.amount_captured,
@@ -820,7 +830,7 @@ where
{
// If the operation is confirm, we will send session token response in next action
if format!("{operation:?}").eq("PaymentConfirm") {
- payment_attempt
+ let condition1 = payment_attempt
.connector
.as_ref()
.map(|connector| {
@@ -835,7 +845,35 @@ where
Some(false)
}
})
- .unwrap_or(false)
+ .unwrap_or(false);
+
+ let condition2 = payment_attempt
+ .connector
+ .as_ref()
+ .map(|connector| matches!(connector.as_str(), "plaid"))
+ .and_then(|is_connector_supports_third_party_sdk| {
+ if is_connector_supports_third_party_sdk {
+ payment_attempt
+ .payment_method
+ .map(|pm| matches!(pm, diesel_models::enums::PaymentMethod::BankRedirect))
+ .and_then(|first_match| {
+ payment_attempt
+ .payment_method_type
+ .map(|pmt| {
+ matches!(
+ pmt,
+ diesel_models::enums::PaymentMethodType::OpenBanking
+ )
+ })
+ .map(|second_match| first_match && second_match)
+ })
+ } else {
+ Some(false)
+ }
+ })
+ .unwrap_or(false);
+
+ condition1 || condition2
} else {
false
}
@@ -1112,6 +1150,13 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthoriz
.map(|customer| customer.clone().into_inner())
});
+ let customer_id = additional_data
+ .customer_data
+ .as_ref()
+ .map(|data| data.customer_id.clone());
+
+ let conn_transaction_id = payment_data.payment_attempt.connector_transaction_id;
+
Ok(Self {
payment_method_data: payment_method_data.get_required_value("payment_method_data")?,
setup_future_usage: payment_data.payment_intent.setup_future_usage,
@@ -1132,12 +1177,12 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthoriz
order_category,
session_token: None,
enrolled_for_3ds: true,
- related_transaction_id: None,
+ related_transaction_id: conn_transaction_id,
payment_method_type: payment_data.payment_attempt.payment_method_type,
router_return_url,
webhook_url,
complete_authorize_url,
- customer_id: None,
+ customer_id,
surcharge_details: payment_data.surcharge_details,
request_incremental_authorization: matches!(
payment_data
diff --git a/crates/router/src/core/pm_auth.rs b/crates/router/src/core/pm_auth.rs
index 21ba27eac17..125f4b294a5 100644
--- a/crates/router/src/core/pm_auth.rs
+++ b/crates/router/src/core/pm_auth.rs
@@ -197,8 +197,18 @@ impl ForeignTryFrom<&types::ConnectorAuthType> for PlaidAuthType {
Ok::<Self, errors::ConnectorError>(Self {
client_id: api_key.to_owned(),
secret: key1.to_owned(),
+ merchant_data: None,
})
}
+ types::ConnectorAuthType::OpenBankingAuth {
+ api_key,
+ key1,
+ merchant_data,
+ } => Ok::<Self, errors::ConnectorError>(Self {
+ client_id: api_key.to_owned(),
+ secret: key1.to_owned(),
+ merchant_data: Some(merchant_data.clone().into()),
+ }),
_ => Err(errors::ConnectorError::FailedToObtainAuthType),
}
}
diff --git a/crates/router/src/core/pm_auth/transformers.rs b/crates/router/src/core/pm_auth/transformers.rs
index 8a1369c2e02..3209ec95353 100644
--- a/crates/router/src/core/pm_auth/transformers.rs
+++ b/crates/router/src/core/pm_auth/transformers.rs
@@ -2,6 +2,33 @@ use pm_auth::types::{self as pm_auth_types};
use crate::{core::errors, types, types::transformers::ForeignTryFrom};
+impl From<types::MerchantAccountData> for pm_auth_types::MerchantAccountData {
+ fn from(from: types::MerchantAccountData) -> Self {
+ match from {
+ types::MerchantAccountData::Iban { iban, name } => Self::Iban { iban, name },
+ types::MerchantAccountData::Bacs {
+ account_number,
+ sort_code,
+ name,
+ } => Self::Bacs {
+ account_number,
+ sort_code,
+ name,
+ },
+ }
+ }
+}
+
+impl From<types::MerchantRecipientData> for pm_auth_types::MerchantRecipientData {
+ fn from(value: types::MerchantRecipientData) -> Self {
+ match value {
+ types::MerchantRecipientData::RecipientId(id) => Self::RecipientId(id),
+ types::MerchantRecipientData::WalletId(id) => Self::WalletId(id),
+ types::MerchantRecipientData::AccountData(data) => Self::AccountData(data.into()),
+ }
+ }
+}
+
impl ForeignTryFrom<types::ConnectorAuthType> for pm_auth_types::ConnectorAuthType {
type Error = errors::ConnectorError;
fn foreign_try_from(auth_type: types::ConnectorAuthType) -> Result<Self, Self::Error> {
@@ -12,6 +39,15 @@ impl ForeignTryFrom<types::ConnectorAuthType> for pm_auth_types::ConnectorAuthTy
secret: key1.to_owned(),
})
}
+ types::ConnectorAuthType::OpenBankingAuth {
+ api_key,
+ key1,
+ merchant_data,
+ } => Ok::<Self, errors::ConnectorError>(Self::OpenBankingAuth {
+ api_key,
+ key1,
+ merchant_data: merchant_data.into(),
+ }),
_ => Err(errors::ConnectorError::FailedToObtainAuthType),
}
}
diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs
index 5b609b072c1..76147753366 100644
--- a/crates/router/src/types.rs
+++ b/crates/router/src/types.rs
@@ -49,6 +49,8 @@ pub type PaymentsAuthorizeRouterData =
RouterData<api::Authorize, PaymentsAuthorizeData, PaymentsResponseData>;
pub type PaymentsPreProcessingRouterData =
RouterData<api::PreProcessing, PaymentsPreProcessingData, PaymentsResponseData>;
+pub type PaymentsPostProcessingRouterData =
+ RouterData<api::PostProcessing, PaymentsPostProcessingData, PaymentsResponseData>;
pub type PaymentsAuthorizeSessionTokenRouterData =
RouterData<api::AuthorizeSessionToken, AuthorizeSessionTokenData, PaymentsResponseData>;
pub type PaymentsCompleteAuthorizeRouterData =
@@ -130,6 +132,11 @@ pub type PaymentsPreProcessingType = dyn services::ConnectorIntegration<
PaymentsPreProcessingData,
PaymentsResponseData,
>;
+pub type PaymentsPostProcessingType = dyn services::ConnectorIntegration<
+ api::PostProcessing,
+ PaymentsPostProcessingData,
+ PaymentsResponseData,
+>;
pub type PaymentsCompleteAuthorizeType = dyn services::ConnectorIntegration<
api::CompleteAuthorize,
CompleteAuthorizeData,
@@ -501,6 +508,24 @@ pub struct PaymentsPreProcessingData {
pub redirect_response: Option<CompleteAuthorizeRedirectResponse>,
}
+#[derive(Debug, Clone)]
+pub struct PaymentsPostProcessingData {
+ pub payment_method_data: payments::PaymentMethodData,
+ pub amount: i64,
+ pub email: Option<Email>,
+ pub customer_id: Option<String>,
+ pub currency: storage_enums::Currency,
+ pub payment_method_type: Option<storage_enums::PaymentMethodType>,
+ pub setup_mandate_details: Option<MandateData>,
+ pub capture_method: Option<storage_enums::CaptureMethod>,
+ pub order_details: Option<Vec<api_models::payments::OrderDetailsWithAmount>>,
+ pub router_return_url: Option<String>,
+ pub webhook_url: Option<String>,
+ pub complete_authorize_url: Option<String>,
+ pub browser_info: Option<BrowserInformation>,
+ pub connector_transaction_id: Option<String>,
+}
+
#[derive(Debug, Clone)]
pub struct CompleteAuthorizeData {
pub payment_method_data: Option<payments::PaymentMethodData>,
@@ -931,6 +956,9 @@ pub enum PaymentsResponseData {
error_code: Option<String>,
error_message: Option<String>,
},
+ PostProcessingResponse {
+ session_token: Option<api::OpenBankingSessionToken>,
+ },
}
#[derive(Debug, Clone)]
@@ -1150,6 +1178,88 @@ pub struct MandateRevokeResponseData {
pub mandate_status: MandateStatus,
}
+#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum MerchantAccountData {
+ Iban {
+ iban: Secret<String>,
+ name: String,
+ },
+ Bacs {
+ account_number: Secret<String>,
+ sort_code: Secret<String>,
+ name: String,
+ },
+}
+
+impl ForeignFrom<MerchantAccountData> for api_models::admin::MerchantAccountData {
+ fn foreign_from(from: MerchantAccountData) -> Self {
+ match from {
+ MerchantAccountData::Iban { iban, name } => Self::Iban { iban, name },
+ MerchantAccountData::Bacs {
+ account_number,
+ sort_code,
+ name,
+ } => Self::Bacs {
+ account_number,
+ sort_code,
+ name,
+ },
+ }
+ }
+}
+
+impl From<api_models::admin::MerchantAccountData> for MerchantAccountData {
+ fn from(from: api_models::admin::MerchantAccountData) -> Self {
+ match from {
+ api_models::admin::MerchantAccountData::Iban { iban, name } => {
+ Self::Iban { iban, name }
+ }
+ api_models::admin::MerchantAccountData::Bacs {
+ account_number,
+ sort_code,
+ name,
+ } => Self::Bacs {
+ account_number,
+ sort_code,
+ name,
+ },
+ }
+ }
+}
+
+#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum MerchantRecipientData {
+ RecipientId(Secret<String>),
+ WalletId(Secret<String>),
+ AccountData(MerchantAccountData),
+}
+
+impl ForeignFrom<MerchantRecipientData> for api_models::admin::MerchantRecipientData {
+ fn foreign_from(value: MerchantRecipientData) -> Self {
+ match value {
+ MerchantRecipientData::RecipientId(id) => Self::RecipientId(id),
+ MerchantRecipientData::WalletId(id) => Self::WalletId(id),
+ MerchantRecipientData::AccountData(data) => {
+ Self::AccountData(api_models::admin::MerchantAccountData::foreign_from(data))
+ }
+ }
+ }
+}
+
+impl From<api_models::admin::MerchantRecipientData> for MerchantRecipientData {
+ fn from(value: api_models::admin::MerchantRecipientData) -> Self {
+ match value {
+ api_models::admin::MerchantRecipientData::RecipientId(id) => Self::RecipientId(id),
+ api_models::admin::MerchantRecipientData::WalletId(id) => Self::WalletId(id),
+ api_models::admin::MerchantRecipientData::AccountData(data) => {
+ Self::AccountData(data.into())
+ }
+ }
+ }
+}
+
// Different patterns of authentication.
#[derive(Default, Debug, Clone, serde::Deserialize, serde::Serialize)]
#[serde(tag = "auth_type")]
@@ -1176,6 +1286,11 @@ pub enum ConnectorAuthType {
CurrencyAuthKey {
auth_key_map: HashMap<storage_enums::Currency, pii::SecretSerdeValue>,
},
+ OpenBankingAuth {
+ api_key: Secret<String>,
+ key1: Secret<String>,
+ merchant_data: MerchantRecipientData,
+ },
#[default]
NoKey,
}
@@ -1214,6 +1329,15 @@ impl From<api_models::admin::ConnectorAuthType> for ConnectorAuthType {
Self::CurrencyAuthKey { auth_key_map }
}
api_models::admin::ConnectorAuthType::NoKey => Self::NoKey,
+ api_models::admin::ConnectorAuthType::OpenBankingAuth {
+ api_key,
+ key1,
+ merchant_data,
+ } => Self::OpenBankingAuth {
+ api_key,
+ key1,
+ merchant_data: merchant_data.into(),
+ },
}
}
}
@@ -1248,6 +1372,17 @@ impl ForeignFrom<ConnectorAuthType> for api_models::admin::ConnectorAuthType {
Self::CurrencyAuthKey { auth_key_map }
}
ConnectorAuthType::NoKey => Self::NoKey,
+ ConnectorAuthType::OpenBankingAuth {
+ api_key,
+ key1,
+ merchant_data,
+ } => Self::OpenBankingAuth {
+ api_key,
+ key1,
+ merchant_data: api_models::admin::MerchantRecipientData::foreign_from(
+ merchant_data,
+ ),
+ },
}
}
}
diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs
index 50d256b034b..786228ba484 100644
--- a/crates/router/src/types/api.rs
+++ b/crates/router/src/types/api.rs
@@ -363,6 +363,7 @@ impl ConnectorData {
enums::Connector::Payme => Ok(Box::new(&connector::Payme)),
enums::Connector::Payu => Ok(Box::new(&connector::Payu)),
enums::Connector::Placetopay => Ok(Box::new(&connector::Placetopay)),
+ enums::Connector::Plaid => Ok(Box::new(&connector::Plaid)),
enums::Connector::Powertranz => Ok(Box::new(&connector::Powertranz)),
enums::Connector::Prophetpay => Ok(Box::new(&connector::Prophetpay)),
enums::Connector::Rapyd => Ok(Box::new(&connector::Rapyd)),
@@ -381,7 +382,6 @@ impl ConnectorData {
enums::Connector::Volt => Ok(Box::new(&connector::Volt)),
enums::Connector::Zen => Ok(Box::new(&connector::Zen)),
enums::Connector::Signifyd
- | enums::Connector::Plaid
| enums::Connector::Riskified
| enums::Connector::Threedsecureio => {
Err(report!(errors::ConnectorError::InvalidConnectorName)
diff --git a/crates/router/src/types/api/payments.rs b/crates/router/src/types/api/payments.rs
index 8e13f6c9935..48164e94000 100644
--- a/crates/router/src/types/api/payments.rs
+++ b/crates/router/src/types/api/payments.rs
@@ -2,16 +2,16 @@ pub use api_models::payments::{
AcceptanceType, Address, AddressDetails, Amount, AuthenticationForStartResponse, Card,
CryptoData, CustomerAcceptance, HeaderPayload, MandateAmountData, MandateData,
MandateTransactionType, MandateType, MandateValidationFields, NextActionType, OnlineMandate,
- PayLaterData, PaymentIdType, PaymentListConstraints, PaymentListFilterConstraints,
- PaymentListFilters, PaymentListResponse, PaymentListResponseV2, PaymentMethodData,
- PaymentMethodDataRequest, PaymentMethodDataResponse, PaymentOp, PaymentRetrieveBody,
- PaymentRetrieveBodyWithCredentials, PaymentsApproveRequest, PaymentsCancelRequest,
- PaymentsCaptureRequest, PaymentsExternalAuthenticationRequest,
+ OpenBankingSessionToken, PayLaterData, PaymentIdType, PaymentListConstraints,
+ PaymentListFilterConstraints, PaymentListFilters, 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,
+ PgRedirectResponse, PhoneDetails, RedirectionResponse, SessionToken, SessionTokenType,
+ TimeRange, UrlDetails, VerifyRequest, VerifyResponse, WalletData,
};
use error_stack::{IntoReport, ResultExt};
@@ -83,6 +83,9 @@ pub struct SetupMandate;
#[derive(Debug, Clone)]
pub struct PreProcessing;
+#[derive(Debug, Clone)]
+pub struct PostProcessing;
+
#[derive(Debug, Clone)]
pub struct IncrementalAuthorization;
@@ -214,6 +217,15 @@ pub trait PaymentsPreProcessing:
{
}
+pub trait PaymentsPostProcessing:
+ api::ConnectorIntegration<
+ PostProcessing,
+ types::PaymentsPostProcessingData,
+ types::PaymentsResponseData,
+>
+{
+}
+
pub trait Payment:
api_types::ConnectorCommon
+ api_types::ConnectorValidation
@@ -228,6 +240,7 @@ pub trait Payment:
+ PaymentSession
+ PaymentToken
+ PaymentsPreProcessing
+ + PaymentsPostProcessing
+ ConnectorCustomer
+ PaymentIncrementalAuthorization
{
diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs
index 29f924fc65b..3c0b424c94c 100644
--- a/crates/router/src/types/transformers.rs
+++ b/crates/router/src/types/transformers.rs
@@ -216,12 +216,7 @@ impl ForeignTryFrom<api_enums::Connector> for common_enums::RoutableConnectors {
api_enums::Connector::Paypal => Self::Paypal,
api_enums::Connector::Payu => Self::Payu,
api_models::enums::Connector::Placetopay => Self::Placetopay,
- api_enums::Connector::Plaid => {
- Err(common_utils::errors::ValidationError::InvalidValue {
- message: "plaid is not a routable connector".to_string(),
- })
- .into_report()?
- }
+ api_enums::Connector::Plaid => Self::Plaid,
api_enums::Connector::Powertranz => Self::Powertranz,
api_enums::Connector::Prophetpay => Self::Prophetpay,
api_enums::Connector::Rapyd => Self::Rapyd,
@@ -417,6 +412,7 @@ impl ForeignFrom<api_enums::PaymentMethodType> for api_enums::PaymentMethod {
| api_enums::PaymentMethodType::OnlineBankingPoland
| api_enums::PaymentMethodType::OnlineBankingSlovakia
| api_enums::PaymentMethodType::OpenBankingUk
+ | api_enums::PaymentMethodType::OpenBanking
| api_enums::PaymentMethodType::Przelewy24
| api_enums::PaymentMethodType::Trustly
| api_enums::PaymentMethodType::Bizum
diff --git a/crates/router/tests/connectors/main.rs b/crates/router/tests/connectors/main.rs
index 8db743d6098..c69158bc293 100644
--- a/crates/router/tests/connectors/main.rs
+++ b/crates/router/tests/connectors/main.rs
@@ -46,6 +46,7 @@ mod payme;
mod paypal;
mod payu;
mod placetopay;
+mod plaid;
mod powertranz;
#[cfg(feature = "dummy_connector")]
mod prophetpay;
diff --git a/crates/router/tests/connectors/plaid.rs b/crates/router/tests/connectors/plaid.rs
new file mode 100644
index 00000000000..d54d3cd6772
--- /dev/null
+++ b/crates/router/tests/connectors/plaid.rs
@@ -0,0 +1,423 @@
+use masking::Secret;
+use router::{
+ core::utils as core_utils,
+ types::{self, api, storage::enums},
+};
+use test_utils::connector_auth;
+
+use crate::utils::{self, ConnectorActions};
+
+#[derive(Clone, Copy)]
+struct PlaidTest;
+impl ConnectorActions for PlaidTest {}
+impl utils::Connector for PlaidTest {
+ fn get_data(&self) -> types::api::ConnectorData {
+ use router::connector::Plaid;
+ types::api::ConnectorData {
+ connector: Box::new(&Plaid),
+ connector_name: types::Connector::Plaid,
+ get_token: types::api::GetToken::Connector,
+ merchant_connector_id: None,
+ }
+ }
+
+ fn get_auth_token(&self) -> types::ConnectorAuthType {
+ utils::to_connector_auth_type(
+ connector_auth::ConnectorAuthentication::new()
+ .plaid
+ .expect("Missing connector authentication configuration")
+ .into(),
+ )
+ }
+
+ fn get_name(&self) -> String {
+ "plaid".to_string()
+ }
+}
+
+static CONNECTOR: PlaidTest = PlaidTest {};
+
+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: router::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: router::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 scenerios
+// 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: types::api::PaymentMethodData::Card(api::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: types::api::PaymentMethodData::Card(api::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: types::api::PaymentMethodData::Card(api::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/sample_auth.toml b/crates/router/tests/connectors/sample_auth.toml
index 3f78ff7f491..5e00249dc10 100644
--- a/crates/router/tests/connectors/sample_auth.toml
+++ b/crates/router/tests/connectors/sample_auth.toml
@@ -119,38 +119,38 @@ api_secret = "Application Identifier"
key1 = "Business Identifier"
[opayo]
-api_key="API Key"
+api_key = "API Key"
[wise]
api_key = "API Key"
key1 = "Profile ID"
[automation_configs]
-hs_base_url="http://localhost:8080"
-hs_test_browser="firefox"
-chrome_profile_path=""
-firefox_profile_path=""
-pypl_email=""
-pypl_pass=""
-gmail_email=""
-gmail_pass=""
+hs_base_url = "http://localhost:8080"
+hs_test_browser = "firefox"
+chrome_profile_path = ""
+firefox_profile_path = ""
+pypl_email = ""
+pypl_pass = ""
+gmail_email = ""
+gmail_pass = ""
[payme]
# Open api key
-api_key="seller payme id"
-key1="payme client key"
+api_key = "seller payme id"
+key1 = "payme client key"
[cryptopay]
api_key = "api_key"
key1 = "key1"
[cashtocode]
-api_key="Classic PMT API Key"
+api_key = "Classic PMT API Key"
key1 = "Evoucher PMT API Key"
[tsys]
-api_key="device id"
+api_key = "device id"
key1 = "transaction key"
api_secret = "developer id"
@@ -159,31 +159,31 @@ api_key = "Partner code"
key1 = "Credential code"
[powertranz]
-api_key="PowerTranz-PowerTranzPassword"
+api_key = "PowerTranz-PowerTranzPassword"
key1 = "PowerTranz-PowerTranzId"
[stax]
-api_key="API Key"
+api_key = "API Key"
[boku]
-api_key="API Key"
+api_key = "API Key"
key1 = "transaction key"
[square]
-api_key="API Key"
+api_key = "API Key"
key1 = "transaction key"
[helcim]
-api_key="API Key"
+api_key = "API Key"
[gocardless]
-api_key="API Key"
+api_key = "API Key"
[volt]
-api_key="API Key"
+api_key = "API Key"
[prophetpay]
-api_key="API Key"
+api_key = "API Key"
[bankofamerica]
api_key = "MyApiKey"
@@ -191,10 +191,12 @@ key1 = "Merchant id"
api_secret = "Secret key"
[placetopay]
-api_key= "Login"
-key1= "Trankey"
+api_key = "Login"
+key1 = "Trankey"
[threedsecureio]
-api_key="API Key"
+api_key = "API Key"
+[plaid]
+api_key = "API Key"
diff --git a/crates/test_utils/src/connector_auth.rs b/crates/test_utils/src/connector_auth.rs
index a2753a2c517..c91a50fce33 100644
--- a/crates/test_utils/src/connector_auth.rs
+++ b/crates/test_utils/src/connector_auth.rs
@@ -49,6 +49,7 @@ pub struct ConnectorAuthentication {
pub paypal: Option<BodyKey>,
pub payu: Option<BodyKey>,
pub placetopay: Option<BodyKey>,
+ pub plaid: Option<HeaderKey>,
pub powertranz: Option<BodyKey>,
pub prophetpay: Option<HeaderKey>,
pub rapyd: Option<BodyKey>,
diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml
index 98a2613f3f2..4c102aad709 100644
--- a/loadtest/config/development.toml
+++ b/loadtest/config/development.toml
@@ -107,6 +107,7 @@ payme.base_url = "https://sandbox.payme.io/"
paypal.base_url = "https://api-m.sandbox.paypal.com/"
payu.base_url = "https://secure.snd.payu.com/"
placetopay.base_url = "https://test.placetopay.com/rest/gateway"
+plaid.base_url = "https://sandbox.plaid.com"
powertranz.base_url = "https://staging.ptranz.com/api/"
prophetpay.base_url = "https://ccm-thirdparty.cps.golf/"
rapyd.base_url = "https://sandboxapi.rapyd.net"
@@ -172,6 +173,7 @@ cards = [
"paypal",
"payu",
"placetopay",
+ "plaid",
"powertranz",
"prophetpay",
"shift4",
diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json
index 4f6a4410cb8..251a0de4e81 100644
--- a/openapi/openapi_spec.json
+++ b/openapi/openapi_spec.json
@@ -16067,7 +16067,8 @@
"wise",
"worldline",
"worldpay",
- "zen"
+ "zen",
+ "plaid"
]
},
"RoutingAlgorithm": {
diff --git a/scripts/add_connector.sh b/scripts/add_connector.sh
index 2be49d123b0..9ec7c031406 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 airwallex applepay authorizedotnet bambora bankofamerica bitpay bluesnap boku braintree cashtocode checkout coinbase cryptopay cybersource dlocal dummyconnector fiserv forte globalpay globepay gocardless helcim iatapay klarna mollie multisafepay nexinets noon nuvei opayo opennode payeezy payme paypal payu placetopay powertranz prophetpay rapyd shift4 square stax stripe threedsecureio trustpay tsys volt wise worldline worldpay "$1")
+ connectors=(aci adyen airwallex applepay authorizedotnet bambora bankofamerica bitpay bluesnap boku braintree cashtocode checkout coinbase cryptopay cybersource dlocal dummyconnector fiserv forte globalpay globepay gocardless helcim iatapay klarna mollie multisafepay nexinets noon nuvei opayo opennode payeezy payme paypal payu placetopay plaid powertranz prophetpay rapyd shift4 square stax stripe threedsecureio trustpay tsys volt wise worldline worldpay "$1")
IFS=$'\n' sorted=($(sort <<<"${connectors[*]}")); unset IFS
res=`echo ${sorted[@]}`
sed -i'' -e "s/^ connectors=.*/ connectors=($res \"\$1\")/" $self.tmp
|
2024-03-11T09:25:55Z
|
## 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 -->
Webhook Implementation for Plaid
### 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
7391416e2473eab0474bd01bb155a9ecc96da263
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4002
|
Bug: ci: add a step in `check-msrv` get the rust version from `Cargo.toml`
In the CI-pr workflow we had hardcoded rust-version to be installed for the check-msrv. This pr adds a step to get rust version from Cargo.toml.
|
2024-03-07T07:54:56Z
|
## 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 -->
In the `CI-pr` workflow we had hardcoded `rust-version` to be installed for the `check-msrv`. This pr adds a step to get rust version from `Cargo.toml`.
### 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)?
-->
`Check compilation on MSRV toolchain (ubuntu-latest)` has run successfully on this pr. No other testing required.
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
6671bff3b11e9548a0085046d2594cad9f2571e2
|
||
juspay/hyperswitch
|
juspay__hyperswitch-4030
|
Bug: [GlobalSearch] - API support for free form text search
These would involve getting a string from the user & searching for that string in ES, using the msearch can be considered optional here.
(don't build support for specific key/value or time range filters yet) + deployment
build msearch API + separate index search API...
|
diff --git a/Cargo.lock b/Cargo.lock
index 7c7b2b9a761..e3c39b71842 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -55,7 +55,7 @@ dependencies = [
"flate2",
"futures-core",
"h2",
- "http",
+ "http 0.2.9",
"httparse",
"httpdate",
"itoa",
@@ -128,7 +128,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d66ff4d247d2b160861fa2866457e85706833527840e4133f8f49aa423a38799"
dependencies = [
"bytestring",
- "http",
+ "http 0.2.9",
"regex",
"serde",
"tracing",
@@ -183,10 +183,10 @@ dependencies = [
"actix-service",
"actix-utils",
"futures-core",
- "http",
+ "http 0.2.9",
"impl-more",
"pin-project-lite",
- "rustls 0.21.7",
+ "rustls 0.21.10",
"rustls-webpki",
"tokio 1.36.0",
"tokio-rustls 0.23.4",
@@ -229,7 +229,7 @@ dependencies = [
"encoding_rs",
"futures-core",
"futures-util",
- "http",
+ "http 0.2.9",
"itoa",
"language-tags",
"log",
@@ -340,9 +340,9 @@ dependencies = [
"actix-web",
"api_models",
"async-trait",
- "aws-config",
+ "aws-config 1.1.7",
"aws-sdk-lambda",
- "aws-smithy-types",
+ "aws-smithy-types 1.1.7",
"bigdecimal",
"common_utils",
"diesel_models",
@@ -352,6 +352,7 @@ dependencies = [
"hyperswitch_interfaces",
"masking",
"once_cell",
+ "opensearch",
"reqwest",
"router_env",
"serde",
@@ -621,7 +622,7 @@ dependencies = [
"futures-core",
"futures-util",
"h2",
- "http",
+ "http 0.2.9",
"itoa",
"log",
"mime",
@@ -641,23 +642,23 @@ version = "0.55.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bcdcf0d683fe9c23d32cf5b53c9918ea0a500375a9fb20109802552658e576c9"
dependencies = [
- "aws-credential-types",
+ "aws-credential-types 0.55.3",
"aws-http",
- "aws-sdk-sso",
- "aws-sdk-sts",
- "aws-smithy-async",
+ "aws-sdk-sso 0.28.0",
+ "aws-sdk-sts 0.28.0",
+ "aws-smithy-async 0.55.3",
"aws-smithy-client",
- "aws-smithy-http",
+ "aws-smithy-http 0.55.3",
"aws-smithy-http-tower",
- "aws-smithy-json",
- "aws-smithy-types",
- "aws-types",
+ "aws-smithy-json 0.55.3",
+ "aws-smithy-types 0.55.3",
+ "aws-types 0.55.3",
"bytes 1.5.0",
"fastrand 1.9.0",
"hex",
- "http",
+ "http 0.2.9",
"hyper",
- "ring",
+ "ring 0.16.20",
"time",
"tokio 1.36.0",
"tower",
@@ -665,30 +666,72 @@ dependencies = [
"zeroize",
]
+[[package]]
+name = "aws-config"
+version = "1.1.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0b96342ea8948ab9bef3e6234ea97fc32e2d8a88d8fb6a084e52267317f94b6b"
+dependencies = [
+ "aws-credential-types 1.1.7",
+ "aws-runtime",
+ "aws-sdk-sso 1.15.0",
+ "aws-sdk-ssooidc",
+ "aws-sdk-sts 1.15.0",
+ "aws-smithy-async 1.1.7",
+ "aws-smithy-http 0.60.6",
+ "aws-smithy-json 0.60.6",
+ "aws-smithy-runtime",
+ "aws-smithy-runtime-api",
+ "aws-smithy-types 1.1.7",
+ "aws-types 1.1.7",
+ "bytes 1.5.0",
+ "fastrand 2.0.1",
+ "hex",
+ "http 0.2.9",
+ "hyper",
+ "ring 0.17.8",
+ "time",
+ "tokio 1.36.0",
+ "tracing",
+ "zeroize",
+]
+
[[package]]
name = "aws-credential-types"
version = "0.55.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fcdb2f7acbc076ff5ad05e7864bdb191ca70a6fd07668dc3a1a8bcd051de5ae"
dependencies = [
- "aws-smithy-async",
- "aws-smithy-types",
+ "aws-smithy-async 0.55.3",
+ "aws-smithy-types 0.55.3",
"fastrand 1.9.0",
"tokio 1.36.0",
"tracing",
"zeroize",
]
+[[package]]
+name = "aws-credential-types"
+version = "1.1.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "273fa47dafc9ef14c2c074ddddbea4561ff01b7f68d5091c0e9737ced605c01d"
+dependencies = [
+ "aws-smithy-async 1.1.7",
+ "aws-smithy-runtime-api",
+ "aws-smithy-types 1.1.7",
+ "zeroize",
+]
+
[[package]]
name = "aws-endpoint"
version = "0.55.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8cce1c41a6cfaa726adee9ebb9a56fcd2bbfd8be49fd8a04c5e20fd968330b04"
dependencies = [
- "aws-smithy-http",
- "aws-smithy-types",
- "aws-types",
- "http",
+ "aws-smithy-http 0.55.3",
+ "aws-smithy-types 0.55.3",
+ "aws-types 0.55.3",
+ "http 0.2.9",
"regex",
"tracing",
]
@@ -699,12 +742,12 @@ version = "0.55.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aadbc44e7a8f3e71c8b374e03ecd972869eb91dd2bc89ed018954a52ba84bc44"
dependencies = [
- "aws-credential-types",
- "aws-smithy-http",
- "aws-smithy-types",
- "aws-types",
+ "aws-credential-types 0.55.3",
+ "aws-smithy-http 0.55.3",
+ "aws-smithy-types 0.55.3",
+ "aws-types 0.55.3",
"bytes 1.5.0",
- "http",
+ "http 0.2.9",
"http-body",
"lazy_static",
"percent-encoding",
@@ -712,25 +755,48 @@ dependencies = [
"tracing",
]
+[[package]]
+name = "aws-runtime"
+version = "1.1.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6e38bab716c8bf07da24be07ecc02e0f5656ce8f30a891322ecdcb202f943b85"
+dependencies = [
+ "aws-credential-types 1.1.7",
+ "aws-sigv4 1.1.7",
+ "aws-smithy-async 1.1.7",
+ "aws-smithy-http 0.60.6",
+ "aws-smithy-runtime-api",
+ "aws-smithy-types 1.1.7",
+ "aws-types 1.1.7",
+ "bytes 1.5.0",
+ "fastrand 2.0.1",
+ "http 0.2.9",
+ "http-body",
+ "percent-encoding",
+ "pin-project-lite",
+ "tracing",
+ "uuid",
+]
+
[[package]]
name = "aws-sdk-kms"
version = "0.28.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "545335abd7c6ef7285d2972a67b9f8279ff5fec8bbb3ffc637fa436ba1e6e434"
dependencies = [
- "aws-credential-types",
+ "aws-credential-types 0.55.3",
"aws-endpoint",
"aws-http",
"aws-sig-auth",
- "aws-smithy-async",
+ "aws-smithy-async 0.55.3",
"aws-smithy-client",
- "aws-smithy-http",
+ "aws-smithy-http 0.55.3",
"aws-smithy-http-tower",
- "aws-smithy-json",
- "aws-smithy-types",
- "aws-types",
+ "aws-smithy-json 0.55.3",
+ "aws-smithy-types 0.55.3",
+ "aws-types 0.55.3",
"bytes 1.5.0",
- "http",
+ "http 0.2.9",
"regex",
"tokio-stream",
"tower",
@@ -739,26 +805,23 @@ dependencies = [
[[package]]
name = "aws-sdk-lambda"
-version = "0.28.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b3ad176ffaa3aafa532246eb6a9f18a7d68da19950704ecc95d33d9dc3c62a9b"
-dependencies = [
- "aws-credential-types",
- "aws-endpoint",
- "aws-http",
- "aws-sig-auth",
- "aws-smithy-async",
- "aws-smithy-client",
- "aws-smithy-http",
- "aws-smithy-http-tower",
- "aws-smithy-json",
- "aws-smithy-types",
- "aws-types",
+version = "1.15.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0c4714bdfe1171542377f84c1034b1c64e3e7544119765f205402ae159b5b9b4"
+dependencies = [
+ "aws-credential-types 1.1.7",
+ "aws-runtime",
+ "aws-smithy-async 1.1.7",
+ "aws-smithy-http 0.60.6",
+ "aws-smithy-json 0.60.6",
+ "aws-smithy-runtime",
+ "aws-smithy-runtime-api",
+ "aws-smithy-types 1.1.7",
+ "aws-types 1.1.7",
"bytes 1.5.0",
- "http",
- "regex",
- "tokio-stream",
- "tower",
+ "http 0.2.9",
+ "once_cell",
+ "regex-lite",
"tracing",
]
@@ -768,23 +831,23 @@ version = "0.28.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fba197193cbb4bcb6aad8d99796b2291f36fa89562ded5d4501363055b0de89f"
dependencies = [
- "aws-credential-types",
+ "aws-credential-types 0.55.3",
"aws-endpoint",
"aws-http",
"aws-sig-auth",
- "aws-sigv4",
- "aws-smithy-async",
+ "aws-sigv4 0.55.3",
+ "aws-smithy-async 0.55.3",
"aws-smithy-checksums",
"aws-smithy-client",
"aws-smithy-eventstream",
- "aws-smithy-http",
+ "aws-smithy-http 0.55.3",
"aws-smithy-http-tower",
- "aws-smithy-json",
- "aws-smithy-types",
- "aws-smithy-xml",
- "aws-types",
+ "aws-smithy-json 0.55.3",
+ "aws-smithy-types 0.55.3",
+ "aws-smithy-xml 0.55.3",
+ "aws-types 0.55.3",
"bytes 1.5.0",
- "http",
+ "http 0.2.9",
"http-body",
"once_cell",
"percent-encoding",
@@ -801,19 +864,19 @@ version = "0.28.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4891169a246b580136f4d3682c11a68b710bdc1027dd7774023fa651a87f10b6"
dependencies = [
- "aws-credential-types",
+ "aws-credential-types 0.55.3",
"aws-endpoint",
"aws-http",
"aws-sig-auth",
- "aws-smithy-async",
+ "aws-smithy-async 0.55.3",
"aws-smithy-client",
- "aws-smithy-http",
+ "aws-smithy-http 0.55.3",
"aws-smithy-http-tower",
- "aws-smithy-json",
- "aws-smithy-types",
- "aws-types",
+ "aws-smithy-json 0.55.3",
+ "aws-smithy-types 0.55.3",
+ "aws-types 0.55.3",
"bytes 1.5.0",
- "http",
+ "http 0.2.9",
"regex",
"tokio-stream",
"tower",
@@ -826,63 +889,130 @@ version = "0.28.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c8b812340d86d4a766b2ca73f740dfd47a97c2dff0c06c8517a16d88241957e4"
dependencies = [
- "aws-credential-types",
+ "aws-credential-types 0.55.3",
"aws-endpoint",
"aws-http",
"aws-sig-auth",
- "aws-smithy-async",
+ "aws-smithy-async 0.55.3",
"aws-smithy-client",
- "aws-smithy-http",
+ "aws-smithy-http 0.55.3",
"aws-smithy-http-tower",
- "aws-smithy-json",
- "aws-smithy-types",
- "aws-types",
+ "aws-smithy-json 0.55.3",
+ "aws-smithy-types 0.55.3",
+ "aws-types 0.55.3",
"bytes 1.5.0",
- "http",
+ "http 0.2.9",
"regex",
"tokio-stream",
"tower",
"tracing",
]
+[[package]]
+name = "aws-sdk-sso"
+version = "1.15.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d84bd3925a17c9adbf6ec65d52104a44a09629d8f70290542beeee69a95aee7f"
+dependencies = [
+ "aws-credential-types 1.1.7",
+ "aws-runtime",
+ "aws-smithy-async 1.1.7",
+ "aws-smithy-http 0.60.6",
+ "aws-smithy-json 0.60.6",
+ "aws-smithy-runtime",
+ "aws-smithy-runtime-api",
+ "aws-smithy-types 1.1.7",
+ "aws-types 1.1.7",
+ "bytes 1.5.0",
+ "http 0.2.9",
+ "once_cell",
+ "regex-lite",
+ "tracing",
+]
+
+[[package]]
+name = "aws-sdk-ssooidc"
+version = "1.15.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2c2dae39e997f58bc4d6292e6244b26ba630c01ab671b6f9f44309de3eb80ab8"
+dependencies = [
+ "aws-credential-types 1.1.7",
+ "aws-runtime",
+ "aws-smithy-async 1.1.7",
+ "aws-smithy-http 0.60.6",
+ "aws-smithy-json 0.60.6",
+ "aws-smithy-runtime",
+ "aws-smithy-runtime-api",
+ "aws-smithy-types 1.1.7",
+ "aws-types 1.1.7",
+ "bytes 1.5.0",
+ "http 0.2.9",
+ "once_cell",
+ "regex-lite",
+ "tracing",
+]
+
[[package]]
name = "aws-sdk-sts"
version = "0.28.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "265fac131fbfc188e5c3d96652ea90ecc676a934e3174eaaee523c6cec040b3b"
dependencies = [
- "aws-credential-types",
+ "aws-credential-types 0.55.3",
"aws-endpoint",
"aws-http",
"aws-sig-auth",
- "aws-smithy-async",
+ "aws-smithy-async 0.55.3",
"aws-smithy-client",
- "aws-smithy-http",
+ "aws-smithy-http 0.55.3",
"aws-smithy-http-tower",
- "aws-smithy-json",
- "aws-smithy-query",
- "aws-smithy-types",
- "aws-smithy-xml",
- "aws-types",
+ "aws-smithy-json 0.55.3",
+ "aws-smithy-query 0.55.3",
+ "aws-smithy-types 0.55.3",
+ "aws-smithy-xml 0.55.3",
+ "aws-types 0.55.3",
"bytes 1.5.0",
- "http",
+ "http 0.2.9",
"regex",
"tower",
"tracing",
]
+[[package]]
+name = "aws-sdk-sts"
+version = "1.15.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "17fd9a53869fee17cea77e352084e1aa71e2c5e323d974c13a9c2bcfd9544c7f"
+dependencies = [
+ "aws-credential-types 1.1.7",
+ "aws-runtime",
+ "aws-smithy-async 1.1.7",
+ "aws-smithy-http 0.60.6",
+ "aws-smithy-json 0.60.6",
+ "aws-smithy-query 0.60.6",
+ "aws-smithy-runtime",
+ "aws-smithy-runtime-api",
+ "aws-smithy-types 1.1.7",
+ "aws-smithy-xml 0.60.6",
+ "aws-types 1.1.7",
+ "http 0.2.9",
+ "once_cell",
+ "regex-lite",
+ "tracing",
+]
+
[[package]]
name = "aws-sig-auth"
version = "0.55.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3b94acb10af0c879ecd5c7bdf51cda6679a0a4f4643ce630905a77673bfa3c61"
dependencies = [
- "aws-credential-types",
- "aws-sigv4",
+ "aws-credential-types 0.55.3",
+ "aws-sigv4 0.55.3",
"aws-smithy-eventstream",
- "aws-smithy-http",
- "aws-types",
- "http",
+ "aws-smithy-http 0.55.3",
+ "aws-types 0.55.3",
+ "http 0.2.9",
"tracing",
]
@@ -893,12 +1023,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9d2ce6f507be68e968a33485ced670111d1cbad161ddbbab1e313c03d37d8f4c"
dependencies = [
"aws-smithy-eventstream",
- "aws-smithy-http",
+ "aws-smithy-http 0.55.3",
"bytes 1.5.0",
"form_urlencoded",
"hex",
"hmac",
- "http",
+ "http 0.2.9",
"once_cell",
"percent-encoding",
"regex",
@@ -907,6 +1037,29 @@ dependencies = [
"tracing",
]
+[[package]]
+name = "aws-sigv4"
+version = "1.1.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8ada00a4645d7d89f296fe0ddbc3fe3554f03035937c849a05d37ddffc1f29a1"
+dependencies = [
+ "aws-credential-types 1.1.7",
+ "aws-smithy-http 0.60.6",
+ "aws-smithy-runtime-api",
+ "aws-smithy-types 1.1.7",
+ "bytes 1.5.0",
+ "form_urlencoded",
+ "hex",
+ "hmac",
+ "http 0.2.9",
+ "http 1.0.0",
+ "once_cell",
+ "percent-encoding",
+ "sha2",
+ "time",
+ "tracing",
+]
+
[[package]]
name = "aws-smithy-async"
version = "0.55.3"
@@ -919,19 +1072,30 @@ dependencies = [
"tokio-stream",
]
+[[package]]
+name = "aws-smithy-async"
+version = "1.1.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fcf7f09a27286d84315dfb9346208abb3b0973a692454ae6d0bc8d803fcce3b4"
+dependencies = [
+ "futures-util",
+ "pin-project-lite",
+ "tokio 1.36.0",
+]
+
[[package]]
name = "aws-smithy-checksums"
version = "0.55.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "07ed8b96d95402f3f6b8b57eb4e0e45ee365f78b1a924faf20ff6e97abf1eae6"
dependencies = [
- "aws-smithy-http",
- "aws-smithy-types",
+ "aws-smithy-http 0.55.3",
+ "aws-smithy-types 0.55.3",
"bytes 1.5.0",
"crc32c",
"crc32fast",
"hex",
- "http",
+ "http 0.2.9",
"http-body",
"md-5",
"pin-project-lite",
@@ -946,13 +1110,13 @@ version = "0.55.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0a86aa6e21e86c4252ad6a0e3e74da9617295d8d6e374d552be7d3059c41cedd"
dependencies = [
- "aws-smithy-async",
- "aws-smithy-http",
+ "aws-smithy-async 0.55.3",
+ "aws-smithy-http 0.55.3",
"aws-smithy-http-tower",
- "aws-smithy-types",
+ "aws-smithy-types 0.55.3",
"bytes 1.5.0",
"fastrand 1.9.0",
- "http",
+ "http 0.2.9",
"http-body",
"hyper",
"hyper-rustls 0.23.2",
@@ -970,7 +1134,7 @@ version = "0.55.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "460c8da5110835e3d9a717c61f5556b20d03c32a1dec57f8fc559b360f733bb8"
dependencies = [
- "aws-smithy-types",
+ "aws-smithy-types 0.55.3",
"bytes 1.5.0",
"crc32fast",
]
@@ -982,11 +1146,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2b3b693869133551f135e1f2c77cb0b8277d9e3e17feaf2213f735857c4f0d28"
dependencies = [
"aws-smithy-eventstream",
- "aws-smithy-types",
+ "aws-smithy-types 0.55.3",
"bytes 1.5.0",
"bytes-utils",
"futures-core",
- "http",
+ "http 0.2.9",
"http-body",
"hyper",
"once_cell",
@@ -998,16 +1162,36 @@ dependencies = [
"tracing",
]
+[[package]]
+name = "aws-smithy-http"
+version = "0.60.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6ca214a6a26f1b7ebd63aa8d4f5e2194095643023f9608edf99a58247b9d80d"
+dependencies = [
+ "aws-smithy-runtime-api",
+ "aws-smithy-types 1.1.7",
+ "bytes 1.5.0",
+ "bytes-utils",
+ "futures-core",
+ "http 0.2.9",
+ "http-body",
+ "once_cell",
+ "percent-encoding",
+ "pin-project-lite",
+ "pin-utils",
+ "tracing",
+]
+
[[package]]
name = "aws-smithy-http-tower"
version = "0.55.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ae4f6c5798a247fac98a867698197d9ac22643596dc3777f0c76b91917616b9"
dependencies = [
- "aws-smithy-http",
- "aws-smithy-types",
+ "aws-smithy-http 0.55.3",
+ "aws-smithy-types 0.55.3",
"bytes 1.5.0",
- "http",
+ "http 0.2.9",
"http-body",
"pin-project-lite",
"tower",
@@ -1020,7 +1204,16 @@ version = "0.55.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "23f9f42fbfa96d095194a632fbac19f60077748eba536eb0b9fecc28659807f8"
dependencies = [
- "aws-smithy-types",
+ "aws-smithy-types 0.55.3",
+]
+
+[[package]]
+name = "aws-smithy-json"
+version = "0.60.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1af80ecf3057fb25fe38d1687e94c4601a7817c6a1e87c1b0635f7ecb644ace5"
+dependencies = [
+ "aws-smithy-types 1.1.7",
]
[[package]]
@@ -1029,10 +1222,62 @@ version = "0.55.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "98819eb0b04020a1c791903533b638534ae6c12e2aceda3e6e6fba015608d51d"
dependencies = [
- "aws-smithy-types",
+ "aws-smithy-types 0.55.3",
"urlencoding",
]
+[[package]]
+name = "aws-smithy-query"
+version = "0.60.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "eb27084f72ea5fc20033efe180618677ff4a2f474b53d84695cfe310a6526cbc"
+dependencies = [
+ "aws-smithy-types 1.1.7",
+ "urlencoding",
+]
+
+[[package]]
+name = "aws-smithy-runtime"
+version = "1.1.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fbb5fca54a532a36ff927fbd7407a7c8eb9c3b4faf72792ba2965ea2cad8ed55"
+dependencies = [
+ "aws-smithy-async 1.1.7",
+ "aws-smithy-http 0.60.6",
+ "aws-smithy-runtime-api",
+ "aws-smithy-types 1.1.7",
+ "bytes 1.5.0",
+ "fastrand 2.0.1",
+ "h2",
+ "http 0.2.9",
+ "http-body",
+ "hyper",
+ "hyper-rustls 0.24.2",
+ "once_cell",
+ "pin-project-lite",
+ "pin-utils",
+ "rustls 0.21.10",
+ "tokio 1.36.0",
+ "tracing",
+]
+
+[[package]]
+name = "aws-smithy-runtime-api"
+version = "1.1.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "22389cb6f7cac64f266fb9f137745a9349ced7b47e0d2ba503e9e40ede4f7060"
+dependencies = [
+ "aws-smithy-async 1.1.7",
+ "aws-smithy-types 1.1.7",
+ "bytes 1.5.0",
+ "http 0.2.9",
+ "http 1.0.0",
+ "pin-project-lite",
+ "tokio 1.36.0",
+ "tracing",
+ "zeroize",
+]
+
[[package]]
name = "aws-smithy-types"
version = "0.55.3"
@@ -1046,6 +1291,29 @@ dependencies = [
"time",
]
+[[package]]
+name = "aws-smithy-types"
+version = "1.1.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f081da5481210523d44ffd83d9f0740320050054006c719eae0232d411f024d3"
+dependencies = [
+ "base64-simd",
+ "bytes 1.5.0",
+ "bytes-utils",
+ "futures-core",
+ "http 0.2.9",
+ "http-body",
+ "itoa",
+ "num-integer",
+ "pin-project-lite",
+ "pin-utils",
+ "ryu",
+ "serde",
+ "time",
+ "tokio 1.36.0",
+ "tokio-util",
+]
+
[[package]]
name = "aws-smithy-xml"
version = "0.55.3"
@@ -1055,18 +1323,42 @@ dependencies = [
"xmlparser",
]
+[[package]]
+name = "aws-smithy-xml"
+version = "0.60.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0fccd8f595d0ca839f9f2548e66b99514a85f92feb4c01cf2868d93eb4888a42"
+dependencies = [
+ "xmlparser",
+]
+
[[package]]
name = "aws-types"
version = "0.55.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6dd209616cc8d7bfb82f87811a5c655dc97537f592689b18743bddf5dc5c4829"
dependencies = [
- "aws-credential-types",
- "aws-smithy-async",
+ "aws-credential-types 0.55.3",
+ "aws-smithy-async 0.55.3",
"aws-smithy-client",
- "aws-smithy-http",
- "aws-smithy-types",
- "http",
+ "aws-smithy-http 0.55.3",
+ "aws-smithy-types 0.55.3",
+ "http 0.2.9",
+ "rustc_version 0.4.0",
+ "tracing",
+]
+
+[[package]]
+name = "aws-types"
+version = "1.1.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d07c63521aa1ea9a9f92a701f1a08ce3fd20b46c6efc0d5c8947c1fd879e3df1"
+dependencies = [
+ "aws-credential-types 1.1.7",
+ "aws-smithy-async 1.1.7",
+ "aws-smithy-runtime-api",
+ "aws-smithy-types 1.1.7",
+ "http 0.2.9",
"rustc_version 0.4.0",
"tracing",
]
@@ -1082,7 +1374,7 @@ dependencies = [
"bitflags 1.3.2",
"bytes 1.5.0",
"futures-util",
- "http",
+ "http 0.2.9",
"http-body",
"hyper",
"itoa",
@@ -1108,7 +1400,7 @@ dependencies = [
"async-trait",
"bytes 1.5.0",
"futures-util",
- "http",
+ "http 0.2.9",
"http-body",
"mime",
"rustversion",
@@ -1663,7 +1955,7 @@ dependencies = [
"fake",
"futures 0.3.28",
"hex",
- "http",
+ "http 0.2.9",
"masking",
"md5",
"nanoid",
@@ -1674,7 +1966,7 @@ dependencies = [
"rand 0.8.5",
"regex",
"reqwest",
- "ring",
+ "ring 0.16.20",
"router_env",
"rustc-hash",
"serde",
@@ -2494,11 +2786,11 @@ name = "external_services"
version = "0.1.0"
dependencies = [
"async-trait",
- "aws-config",
+ "aws-config 0.55.3",
"aws-sdk-kms",
"aws-sdk-s3",
"aws-sdk-sesv2",
- "aws-sdk-sts",
+ "aws-sdk-sts 0.28.0",
"aws-smithy-client",
"base64 0.21.5",
"common_utils",
@@ -2537,7 +2829,7 @@ dependencies = [
"cookie 0.16.2",
"futures-core",
"futures-util",
- "http",
+ "http 0.2.9",
"hyper",
"hyper-rustls 0.23.2",
"mime",
@@ -2962,7 +3254,7 @@ dependencies = [
"futures-core",
"futures-sink",
"futures-util",
- "http",
+ "http 0.2.9",
"indexmap 2.1.0",
"slab",
"tokio 1.36.0",
@@ -3013,7 +3305,7 @@ dependencies = [
"base64 0.21.5",
"bytes 1.5.0",
"headers-core",
- "http",
+ "http 0.2.9",
"httpdate",
"mime",
"sha1",
@@ -3025,7 +3317,7 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7f66481bfee273957b1f20485a4ff3362987f85b2c236580d81b4eb7a326429"
dependencies = [
- "http",
+ "http 0.2.9",
]
[[package]]
@@ -3078,6 +3370,17 @@ dependencies = [
"itoa",
]
+[[package]]
+name = "http"
+version = "1.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b32afd38673a8016f7c9ae69e5af41a58f81b1d31689040f2f1959594ce194ea"
+dependencies = [
+ "bytes 1.5.0",
+ "fnv",
+ "itoa",
+]
+
[[package]]
name = "http-body"
version = "0.4.5"
@@ -3085,7 +3388,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d5f38f16d184e36f2408a55281cd658ecbd3ca05cce6d6510a176eca393e26d1"
dependencies = [
"bytes 1.5.0",
- "http",
+ "http 0.2.9",
"pin-project-lite",
]
@@ -3099,7 +3402,7 @@ dependencies = [
"async-channel",
"base64 0.13.1",
"futures-lite",
- "http",
+ "http 0.2.9",
"infer 0.2.3",
"pin-project-lite",
"rand 0.7.3",
@@ -3142,7 +3445,7 @@ dependencies = [
"futures-core",
"futures-util",
"h2",
- "http",
+ "http 0.2.9",
"http-body",
"httparse",
"httpdate",
@@ -3164,7 +3467,7 @@ dependencies = [
"bytes 1.5.0",
"futures 0.3.28",
"headers",
- "http",
+ "http 0.2.9",
"hyper",
"hyper-tls",
"native-tls",
@@ -3179,7 +3482,7 @@ version = "0.23.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1788965e61b367cd03a62950836d5cd41560c3577d90e40e0819373194d1661c"
dependencies = [
- "http",
+ "http 0.2.9",
"hyper",
"log",
"rustls 0.20.9",
@@ -3195,9 +3498,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec3efd23720e2049821a693cbc7e65ea87c72f1c58ff2f9522ff332b1491e590"
dependencies = [
"futures-util",
- "http",
+ "http 0.2.9",
"hyper",
- "rustls 0.21.7",
+ "log",
+ "rustls 0.21.10",
+ "rustls-native-certs",
"tokio 1.36.0",
"tokio-rustls 0.24.1",
]
@@ -3508,7 +3813,7 @@ checksum = "6971da4d9c3aa03c3d8f3ff0f4155b534aad021292003895a469716b2a230378"
dependencies = [
"base64 0.21.5",
"pem",
- "ring",
+ "ring 0.16.20",
"serde",
"serde_json",
"simple_asn1",
@@ -4111,6 +4416,30 @@ dependencies = [
"utoipa",
]
+[[package]]
+name = "opensearch"
+version = "2.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fd2846759315751e04d8b45a0bdbd89ce442282ffb916cf54f6b0adf8df4b44c"
+dependencies = [
+ "aws-credential-types 1.1.7",
+ "aws-sigv4 1.1.7",
+ "aws-smithy-runtime-api",
+ "aws-types 1.1.7",
+ "base64 0.21.5",
+ "bytes 1.5.0",
+ "dyn-clone",
+ "lazy_static",
+ "percent-encoding",
+ "reqwest",
+ "rustc_version 0.4.0",
+ "serde",
+ "serde_json",
+ "serde_with",
+ "url",
+ "void",
+]
+
[[package]]
name = "openssl"
version = "0.10.60"
@@ -4174,7 +4503,7 @@ dependencies = [
"async-trait",
"futures 0.3.28",
"futures-util",
- "http",
+ "http 0.2.9",
"opentelemetry",
"opentelemetry-proto",
"prost",
@@ -4569,7 +4898,7 @@ dependencies = [
"common_enums",
"common_utils",
"error-stack",
- "http",
+ "http 0.2.9",
"masking",
"mime",
"router_derive",
@@ -5058,6 +5387,12 @@ dependencies = [
"regex-syntax 0.6.29",
]
+[[package]]
+name = "regex-lite"
+version = "0.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "30b661b2f27137bdbc16f00eda72866a92bb28af1753ffbd56744fb6e2e9cd8e"
+
[[package]]
name = "regex-syntax"
version = "0.6.29"
@@ -5098,7 +5433,7 @@ dependencies = [
"futures-core",
"futures-util",
"h2",
- "http",
+ "http 0.2.9",
"http-body",
"hyper",
"hyper-rustls 0.24.2",
@@ -5112,7 +5447,7 @@ dependencies = [
"once_cell",
"percent-encoding",
"pin-project-lite",
- "rustls 0.21.7",
+ "rustls 0.21.10",
"rustls-pemfile",
"serde",
"serde_json",
@@ -5146,12 +5481,27 @@ dependencies = [
"cc",
"libc",
"once_cell",
- "spin",
- "untrusted",
+ "spin 0.5.2",
+ "untrusted 0.7.1",
"web-sys",
"winapi 0.3.9",
]
+[[package]]
+name = "ring"
+version = "0.17.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c17fa4cb658e3583423e915b9f3acc01cceaee1860e33d59ebae66adc3a2dc0d"
+dependencies = [
+ "cc",
+ "cfg-if 1.0.0",
+ "getrandom 0.2.11",
+ "libc",
+ "spin 0.9.8",
+ "untrusted 0.9.0",
+ "windows-sys 0.52.0",
+]
+
[[package]]
name = "rkyv"
version = "0.7.42"
@@ -5244,7 +5594,7 @@ dependencies = [
"external_services",
"futures 0.3.28",
"hex",
- "http",
+ "http 0.2.9",
"hyper",
"hyperswitch_interfaces",
"image",
@@ -5272,7 +5622,7 @@ dependencies = [
"redis_interface",
"regex",
"reqwest",
- "ring",
+ "ring 0.16.20",
"router_derive",
"router_env",
"roxmltree",
@@ -5429,7 +5779,7 @@ dependencies = [
"anyhow",
"async-trait",
"bytes 1.5.0",
- "http",
+ "http 0.2.9",
"reqwest",
"rustify_derive",
"serde",
@@ -5474,19 +5824,19 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1b80e3dec595989ea8510028f30c408a4630db12c9cbb8de34203b89d6577e99"
dependencies = [
"log",
- "ring",
+ "ring 0.16.20",
"sct",
"webpki",
]
[[package]]
name = "rustls"
-version = "0.21.7"
+version = "0.21.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "cd8d6c9f025a446bc4d18ad9632e69aec8f287aa84499ee335599fabd20c3fd8"
+checksum = "f9d5a6813c0759e4609cd494e8e725babae6a2ca7b62a5536a13daaec6fcb7ba"
dependencies = [
"log",
- "ring",
+ "ring 0.17.8",
"rustls-webpki",
"sct",
]
@@ -5514,12 +5864,12 @@ dependencies = [
[[package]]
name = "rustls-webpki"
-version = "0.101.6"
+version = "0.101.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3c7d5dece342910d9ba34d259310cae3e0154b873b35408b787b59bce53d34fe"
+checksum = "8b6275d1ee7a1cd780b64aca7726599a1dbc893b1e64144529e55c3c2f745765"
dependencies = [
- "ring",
- "untrusted",
+ "ring 0.17.8",
+ "untrusted 0.9.0",
]
[[package]]
@@ -5625,8 +5975,8 @@ version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d53dcdb7c9f8158937a7981b48accfd39a43af418591a5d008c7b22b5e1b7ca4"
dependencies = [
- "ring",
- "untrusted",
+ "ring 0.16.20",
+ "untrusted 0.7.1",
]
[[package]]
@@ -6025,6 +6375,12 @@ version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e63cff320ae2c57904679ba7cb63280a3dc4613885beafb148ee7bf9aa9042d"
+[[package]]
+name = "spin"
+version = "0.9.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67"
+
[[package]]
name = "sqlformat"
version = "0.2.2"
@@ -6149,13 +6505,13 @@ dependencies = [
"dyn-clone",
"error-stack",
"futures 0.3.28",
- "http",
+ "http 0.2.9",
"masking",
"mime",
"moka",
"once_cell",
"redis_interface",
- "ring",
+ "ring 0.16.20",
"router_derive",
"router_env",
"serde",
@@ -6428,7 +6784,7 @@ dependencies = [
"cookie 0.16.2",
"fantoccini",
"futures 0.3.28",
- "http",
+ "http 0.2.9",
"log",
"parking_lot 0.12.1",
"serde",
@@ -6710,7 +7066,7 @@ version = "0.24.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c28327cf380ac148141087fbfb9de9d7bd4e84ab5d2c28fbc911d753de8a7081"
dependencies = [
- "rustls 0.21.7",
+ "rustls 0.21.10",
"tokio 1.36.0",
]
@@ -6895,7 +7251,7 @@ dependencies = [
"futures-core",
"futures-util",
"h2",
- "http",
+ "http 0.2.9",
"http-body",
"hyper",
"hyper-timeout",
@@ -7211,6 +7567,12 @@ version = "0.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a156c684c91ea7d62626509bce3cb4e1d9ed5c4d978f7b4352658f96a4c26b4a"
+[[package]]
+name = "untrusted"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
+
[[package]]
name = "url"
version = "2.4.1"
@@ -7300,7 +7662,7 @@ dependencies = [
"async-trait",
"bytes 1.5.0",
"derive_builder",
- "http",
+ "http 0.2.9",
"reqwest",
"rustify",
"rustify_derive",
@@ -7336,6 +7698,12 @@ version = "0.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f"
+[[package]]
+name = "void"
+version = "1.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6a02e4885ed3bc0f2de90ea6dd45ebcbb66dacffe03547fadbb0eeae2770887d"
+
[[package]]
name = "vsimd"
version = "0.8.0"
@@ -7473,7 +7841,7 @@ dependencies = [
"base64 0.13.1",
"bytes 1.5.0",
"cookie 0.16.2",
- "http",
+ "http 0.2.9",
"log",
"serde",
"serde_derive",
@@ -7489,8 +7857,8 @@ version = "0.22.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "07ecc0cd7cac091bf682ec5efa18b1cff79d617b84181f38b3951dbe135f607f"
dependencies = [
- "ring",
- "untrusted",
+ "ring 0.16.20",
+ "untrusted 0.7.1",
]
[[package]]
diff --git a/config/config.example.toml b/config/config.example.toml
index 2ffb69c3e3d..daf554f00ad 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -54,10 +54,10 @@ use_legacy_version = false # Resp protocol for fred crate (set this to tr
stream_read_count = 1 # Default number of entries to read from stream if not provided in stream read options
auto_pipeline = true # Whether or not the client should automatically pipeline commands across tasks when possible.
disable_auto_backpressure = false # Whether or not to disable the automatic backpressure features when pipelining is enabled.
-max_in_flight_commands = 5000 # The maximum number of in-flight commands (per connection) before backpressure will be applied.
-default_command_timeout = 30 # An optional timeout to apply to all commands. In seconds
-unresponsive_timeout = 10 # An optional timeout for Unresponsive commands in seconds. This should be less than default_command_timeout.
-max_feed_count = 200 # The maximum number of frames that will be fed to a socket before flushing.
+max_in_flight_commands = 5000 # The maximum number of in-flight commands (per connection) before backpressure will be applied.
+default_command_timeout = 30 # An optional timeout to apply to all commands. In seconds
+unresponsive_timeout = 10 # An optional timeout for Unresponsive commands in seconds. This should be less than default_command_timeout.
+max_feed_count = 200 # The maximum number of frames that will be fed to a socket before flushing.
# This section provides configs for currency conversion api
[forex_api]
@@ -298,9 +298,9 @@ lock_ttl = 160 # the ttl being the expiry (in seconds)
# Scheduler server configuration
[scheduler.server]
-port = 3000 # Port on which the server will listen for incoming requests
-host = "127.0.0.1" # Host IP address to bind the server to
-workers = 1 # Number of actix workers to handle incoming requests concurrently
+port = 3000 # Port on which the server will listen for incoming requests
+host = "127.0.0.1" # Host IP address to bind the server to
+workers = 1 # Number of actix workers to handle incoming requests concurrently
batch_size = 200 # Specifies the batch size the producer will push under a single entry in the redis queue
@@ -321,10 +321,10 @@ paypal = { currency = "USD,INR", country = "US" }
# If either currency or country isn't provided then, all possible values are accepted
[cors]
-max_age = 30 # Maximum time (in seconds) for which this CORS request may be cached.
-origins = "http://localhost:8080" # List of origins that are allowed to make requests.
+max_age = 30 # Maximum time (in seconds) for which this CORS request may be cached.
+origins = "http://localhost:8080" # List of origins that are allowed to make requests.
allowed_methods = "GET,POST,PUT,DELETE" # List of methods that are allowed
-wildcard_origin = false # If true, allows any origin to make requests
+wildcard_origin = false # If true, allows any origin to make requests
# EmailClient configuration. Only applicable when the `email` feature flag is enabled.
[email]
@@ -357,7 +357,7 @@ bluesnap = { payment_method = "card" }
bankofamerica = { payment_method = "card" }
cybersource = { payment_method = "card" }
nmi = { payment_method = "card" }
-payme = {payment_method = "card" }
+payme = { payment_method = "card" }
[dummy_connector]
enabled = true # Whether dummy connector is enabled or not
@@ -380,21 +380,21 @@ 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" } # 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"}
+card.credit = { connector_list = "stripe,adyen,cybersource" } # 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" }
-bank_redirect.giropay = {connector_list = "adyen,globalpay"}
+bank_redirect.giropay = { connector_list = "adyen,globalpay" }
[mandates.update_mandate_supported]
-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
+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
# Required fields info used while listing the payment_method_data
[required_fields.pay_later] # payment_method = "pay_later"
@@ -412,9 +412,9 @@ afterpay_clearpay = { fields = { stripe = [ # payment_method_type = afterpay_cle
payout_eligibility = true # Defaults the eligibility of a payout method to true in case connector does not provide checks for payout eligibility
[pm_filters.adyen]
-sofort = { country = "AT,BE,DE,ES,CH,NL", currency = "CHF,EUR"}
+sofort = { country = "AT,BE,DE,ES,CH,NL", currency = "CHF,EUR" }
paypal = { country = "AU,NZ,CN,JP,HK,MY,TH,KR,PH,ID,AE,KW,BR,ES,GB,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,FI,RO,HR,UA,MT,SI,GI,PT,IE,CZ,EE,LT,LV,IT,PL,IS,CA,US", currency = "AUD,BRL,CAD,CZK,DKK,EUR,HKD,HUF,INR,JPY,MYR,MXN,NZD,NOK,PHP,PLN,RUB,GBP,SGD,SEK,CHF,THB,USD" }
-klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NO,PL,PT,RO,ES,SE,CH,NL,GB,US", currency = "AUD,EUR,CAD,CZK,DKK,NOK,PLN,RON,SEK,CHF,GBP,USD"}
+klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NO,PL,PT,RO,ES,SE,CH,NL,GB,US", currency = "AUD,EUR,CAD,CZK,DKK,NOK,PLN,RON,SEK,CHF,GBP,USD" }
ideal = { country = "NL", currency = "EUR" }
online_banking_fpx = { country = "MY", currency = "MYR" }
online_banking_thailand = { country = "TH", currency = "THB" }
@@ -442,7 +442,7 @@ pay_easy = { country = "JP", currency = "JPY" }
boleto = { country = "BR", currency = "BRL" }
[pm_filters.volt]
-open_banking_uk = {country = "DE,GB,AT,BE,CY,EE,ES,FI,FR,GR,HR,IE,IT,LT,LU,LV,MT,NL,PT,SI,SK,BG,CZ,DK,HU,NO,PL,RO,SE,AU,BR", currency = "EUR,GBP,DKK,NOK,PLN,SEK,AUD,BRL"}
+open_banking_uk = { country = "DE,GB,AT,BE,CY,EE,ES,FI,FR,GR,HR,IE,IT,LT,LU,LV,MT,NL,PT,SI,SK,BG,CZ,DK,HU,NO,PL,RO,SE,AU,BR", currency = "EUR,GBP,DKK,NOK,PLN,SEK,AUD,BRL" }
[pm_filters.zen]
credit = { not_available_flows = { capture_method = "manual" } }
@@ -566,22 +566,36 @@ dispute_analytics_topic = "topic" # Kafka topic to be used for Dispute event
# File storage configuration
[file_storage]
-file_storage_backend = "aws_s3" # File storage backend to be used
+file_storage_backend = "aws_s3" # File storage backend to be used
[file_storage.aws_s3]
-region = "us-east-1" # The AWS region used by the AWS S3 for file storage
-bucket_name = "bucket1" # The AWS S3 bucket name for file storage
+region = "us-east-1" # The AWS region used by the AWS S3 for file storage
+bucket_name = "bucket1" # The AWS S3 bucket name for file storage
[secrets_management]
-secrets_manager = "aws_kms" # Secrets manager client to be used
+secrets_manager = "aws_kms" # Secrets manager client to be used
[secrets_management.aws_kms]
-key_id = "kms_key_id" # The AWS key ID used by the KMS SDK for decrypting data.
-region = "kms_region" # The AWS region used by the KMS SDK for decrypting data.
+key_id = "kms_key_id" # The AWS key ID used by the KMS SDK for decrypting data.
+region = "kms_region" # The AWS region used by the KMS SDK for decrypting data.
[encryption_management]
-encryption_manager = "aws_kms" # Encryption manager client to be used
+encryption_manager = "aws_kms" # Encryption manager client to be used
[encryption_management.aws_kms]
-key_id = "kms_key_id" # The AWS key ID used by the KMS SDK for decrypting data.
-region = "kms_region" # The AWS region used by the KMS SDK for decrypting data.
+key_id = "kms_key_id" # The AWS key ID used by the KMS SDK for decrypting data.
+region = "kms_region" # The AWS region used by the KMS SDK for decrypting data.
+
+[opensearch]
+host = "https://localhost:9200"
+
+[opensearch.auth]
+auth = "basic"
+username = "admin"
+password = "admin"
+region = "eu-central-1"
+
+[opensearch.indexes]
+payment_attempts = "hyperswitch-payment-attempt-events"
+payment_intents = "hyperswitch-payment-intent-events"
+refunds = "hyperswitch-refund-events"
diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml
index 990796c79bc..cfe696e42c0 100644
--- a/config/deployments/env_specific.toml
+++ b/config/deployments/env_specific.toml
@@ -42,13 +42,17 @@ client_secret = "paypal_client_secret"
partner_id = "paypal_partner_id"
[connector_request_reference_id_config]
-merchant_ids_send_payment_id_as_connector_request_id = ["merchant_id_1", "merchant_id_2", "etc.,"]
+merchant_ids_send_payment_id_as_connector_request_id = [
+ "merchant_id_1",
+ "merchant_id_2",
+ "etc.,",
+]
[cors]
-max_age = 30 # Maximum time (in seconds) for which this CORS request may be cached.
-origins = "http://localhost:8080" # List of origins that are allowed to make requests.
+max_age = 30 # Maximum time (in seconds) for which this CORS request may be cached.
+origins = "http://localhost:8080" # List of origins that are allowed to make requests.
allowed_methods = "GET,POST,PUT,DELETE" # List of methods that are allowed
-wildcard_origin = false # If true, allows any origin to make requests
+wildcard_origin = false # If true, allows any origin to make requests
# EmailClient configuration. Only applicable when the `email` feature flag is enabled.
[email]
@@ -160,21 +164,24 @@ https_url = "https://proxy_https_url" # Outgoing proxy https URL to proxy the HT
[redis]
host = "127.0.0.1"
port = 6379
-pool_size = 5 # Number of connections to keep open
-reconnect_max_attempts = 5 # Maximum number of reconnection attempts to make before failing. Set to 0 to retry forever.
-reconnect_delay = 5 # Delay between reconnection attempts, in milliseconds
-default_ttl = 300 # Default TTL for entries, in seconds
-default_hash_ttl = 900 # Default TTL for hashes entries, in seconds
-use_legacy_version = false # RESP protocol for fred crate (set this to true if using RESPv2 or redis version < 6)
-stream_read_count = 1 # Default number of entries to read from stream if not provided in stream read options
-auto_pipeline = true # Whether or not the client should automatically pipeline commands across tasks when possible.
-disable_auto_backpressure = false # Whether or not to disable the automatic backpressure features when pipelining is enabled.
+pool_size = 5 # Number of connections to keep open
+reconnect_max_attempts = 5 # Maximum number of reconnection attempts to make before failing. Set to 0 to retry forever.
+reconnect_delay = 5 # Delay between reconnection attempts, in milliseconds
+default_ttl = 300 # Default TTL for entries, in seconds
+default_hash_ttl = 900 # Default TTL for hashes entries, in seconds
+use_legacy_version = false # RESP protocol for fred crate (set this to true if using RESPv2 or redis version < 6)
+stream_read_count = 1 # Default number of entries to read from stream if not provided in stream read options
+auto_pipeline = true # Whether or not the client should automatically pipeline commands across tasks when possible.
+disable_auto_backpressure = false # Whether or not to disable the automatic backpressure features when pipelining is enabled.
max_in_flight_commands = 5000 # The maximum number of in-flight commands (per connection) before backpressure will be applied.
-default_command_timeout = 30 # An optional timeout to apply to all commands. In seconds
+default_command_timeout = 30 # An optional timeout to apply to all commands. In seconds
unresponsive_timeout = 10 # An optional timeout for Unresponsive commands in seconds. This should be less than default_command_timeout.
-max_feed_count = 200 # The maximum number of frames that will be fed to a socket before flushing.
-cluster_enabled = true # boolean
-cluster_urls = ["redis.cluster.uri-1:8080", "redis.cluster.uri-2:4115"] # List of redis cluster urls
+max_feed_count = 200 # The maximum number of frames that will be fed to a socket before flushing.
+cluster_enabled = true # boolean
+cluster_urls = [
+ "redis.cluster.uri-1:8080",
+ "redis.cluster.uri-2:4115",
+] # List of redis cluster urls
# Replica SQL data store credentials
[replica_database]
@@ -193,6 +200,20 @@ payment_function = "report_download_config_payment_function" # Config to downloa
refund_function = "report_download_config_refund_function" # Config to download refund report
region = "report_download_config_region" # Region of the bucket
+[opensearch]
+host = "https://localhost:9200"
+
+[opensearch.auth]
+auth = "basic"
+username = "admin"
+password = "admin"
+region = "eu-central-1"
+
+[opensearch.indexes]
+payment_attempts = "hyperswitch-payment-attempt-events"
+payment_intents = "hyperswitch-payment-intent-events"
+refunds = "hyperswitch-refund-events"
+
# This section provides some secret values.
[secrets]
master_enc_key = "sample_key" # Master Encryption key used to encrypt merchant wise encryption key. Should be 32-byte long.
@@ -213,15 +234,15 @@ shutdown_timeout = 30
request_body_limit = 32_768
[secrets_management]
-secrets_manager = "aws_kms" # Secrets manager client to be used
+secrets_manager = "aws_kms" # Secrets manager client to be used
[secrets_management.aws_kms]
-key_id = "kms_key_id" # The AWS key ID used by the KMS SDK for decrypting data.
-region = "kms_region" # The AWS region used by the KMS SDK for decrypting data.
+key_id = "kms_key_id" # The AWS key ID used by the KMS SDK for decrypting data.
+region = "kms_region" # The AWS region used by the KMS SDK for decrypting data.
[encryption_management]
-encryption_manager = "aws_kms" # Encryption manager client to be used
+encryption_manager = "aws_kms" # Encryption manager client to be used
[encryption_management.aws_kms]
-key_id = "kms_key_id" # The AWS key ID used by the KMS SDK for decrypting data.
-region = "kms_region" # The AWS region used by the KMS SDK for decrypting data.
+key_id = "kms_key_id" # The AWS key ID used by the KMS SDK for decrypting data.
+region = "kms_region" # The AWS region used by the KMS SDK for decrypting data.
diff --git a/config/development.toml b/config/development.toml
index 16851c90cca..a7abec7fb74 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -273,7 +273,7 @@ adyen = { banks = "blik_psp,place_zipko,m_bank,pay_with_ing,santander_przelew24,
stripe = { banks = "alior_bank,bank_millennium,bank_nowy_bfg_sa,bank_pekao_sa,banki_spbdzielcze,blik,bnp_paribas,boz,citi,credit_agricole,e_transfer_pocztowy24,getin_bank,idea_bank,inteligo,mbank_mtransfer,nest_przelew,noble_pay,pbac_z_ipko,plus_bank,santander_przelew24,toyota_bank,volkswagen_bank" }
[bank_config.open_banking_uk]
-adyen = { banks = "aib,bank_of_scotland,danske_bank,first_direct,first_trust,halifax,lloyds,monzo,nat_west,nationwide_bank,royal_bank_of_scotland,starling,tsb_bank,tesco_bank,ulster_bank,barclays,hsbc_bank,revolut,santander_przelew24,open_bank_success,open_bank_failure,open_bank_cancelled"}
+adyen = { banks = "aib,bank_of_scotland,danske_bank,first_direct,first_trust,halifax,lloyds,monzo,nat_west,nationwide_bank,royal_bank_of_scotland,starling,tsb_bank,tesco_bank,ulster_bank,barclays,hsbc_bank,revolut,santander_przelew24,open_bank_success,open_bank_failure,open_bank_cancelled" }
[bank_config.online_banking_fpx]
adyen.banks = "affin_bank,agro_bank,alliance_bank,am_bank,bank_islam,bank_muamalat,bank_rakyat,bank_simpanan_nasional,cimb_bank,hong_leong_bank,hsbc_bank,kuwait_finance_house,maybank,ocbc_bank,public_bank,rhb_bank,standard_chartered_bank,uob_bank"
@@ -306,7 +306,7 @@ ideal = { country = "NL", currency = "EUR" }
cashapp = { country = "US", currency = "USD" }
[pm_filters.volt]
-open_banking_uk = {country = "DE,GB,AT,BE,CY,EE,ES,FI,FR,GR,HR,IE,IT,LT,LU,LV,MT,NL,PT,SI,SK,BG,CZ,DK,HU,NO,PL,RO,SE,AU,BR", currency = "EUR,GBP,DKK,NOK,PLN,SEK,AUD,BRL"}
+open_banking_uk = { country = "DE,GB,AT,BE,CY,EE,ES,FI,FR,GR,HR,IE,IT,LT,LU,LV,MT,NL,PT,SI,SK,BG,CZ,DK,HU,NO,PL,RO,SE,AU,BR", currency = "EUR,GBP,DKK,NOK,PLN,SEK,AUD,BRL" }
[pm_filters.adyen]
google_pay = { country = "AU,NZ,JP,HK,SG,MY,TH,VN,BH,AE,KW,BR,ES,GB,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,RO,HR,LI,MT,SI,GR,PT,IE,CZ,EE,LT,LV,IT,PL,TR,IS,CA,US", currency = "AED,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BMD,BND,BOB,BRL,BSD,BWP,BYN,BZD,CAD,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HTG,HUF,IDR,ILS,INR,IQD,JMD,JOD,JPY,KES,KGS,KHR,KMF,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LYD,MAD,MDL,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SEK,SGD,SHP,SLE,SOS,SRD,STN,SVC,SZL,THB,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VES,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW" }
@@ -316,54 +316,54 @@ mobile_pay = { country = "DK,FI", currency = "DKK,SEK,NOK,EUR" }
ali_pay = { country = "AU,JP,HK,SG,MY,TH,ES,GB,SE,NO,AT,NL,DE,CY,CH,BE,FR,DK,FI,RO,MT,SI,GR,PT,IE,IT,CA,US", currency = "USD,EUR,GBP,JPY,AUD,SGD,CHF,SEK,NOK,NZD,THB,HKD,CAD" }
we_chat_pay = { country = "AU,NZ,CN,JP,HK,SG,ES,GB,SE,NO,AT,NL,DE,CY,CH,BE,FR,DK,LI,MT,SI,GR,PT,IT,CA,US", currency = "AUD,CAD,CNY,EUR,GBP,HKD,JPY,NZD,SGD,USD" }
mb_way = { country = "PT", currency = "EUR" }
-klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NO,PL,PT,RO,ES,SE,CH,NL,GB,US", currency = "AUD,EUR,CAD,CZK,DKK,NOK,PLN,RON,SEK,CHF,GBP,USD"}
+klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NO,PL,PT,RO,ES,SE,CH,NL,GB,US", currency = "AUD,EUR,CAD,CZK,DKK,NOK,PLN,RON,SEK,CHF,GBP,USD" }
affirm = { country = "US", currency = "USD" }
afterpay_clearpay = { country = "AU,NZ,ES,GB,FR,IT,CA,US", currency = "GBP" }
pay_bright = { country = "CA", currency = "CAD" }
walley = { country = "SE,NO,DK,FI", currency = "DKK,EUR,NOK,SEK" }
giropay = { country = "DE", currency = "EUR" }
eps = { country = "AT", currency = "EUR" }
-sofort = {not_available_flows = { capture_method = "manual" }, country = "AT,BE,DE,ES,CH,NL", currency = "CHF,EUR"}
+sofort = { not_available_flows = { capture_method = "manual" }, country = "AT,BE,DE,ES,CH,NL", currency = "CHF,EUR" }
ideal = { not_available_flows = { capture_method = "manual" }, country = "NL", currency = "EUR" }
-blik = {country = "PL", currency = "PLN"}
-trustly = {country = "ES,GB,SE,NO,AT,NL,DE,DK,FI,EE,LT,LV", currency = "CZK,DKK,EUR,GBP,NOK,SEK"}
-online_banking_czech_republic = {country = "CZ", currency = "EUR,CZK"}
-online_banking_finland = {country = "FI", currency = "EUR"}
-online_banking_poland = {country = "PL", currency = "PLN"}
-online_banking_slovakia = {country = "SK", currency = "EUR,CZK"}
-bancontact_card = {country = "BE", currency = "EUR"}
-ach = {country = "US", currency = "USD"}
-bacs = {country = "GB", currency = "GBP"}
-sepa = {country = "ES,SK,AT,NL,DE,BE,FR,FI,PT,IE,EE,LT,LV,IT", currency = "EUR"}
-ali_pay_hk = {country = "HK", currency = "HKD"}
-bizum = {country = "ES", currency = "EUR"}
-go_pay = {country = "ID", currency = "IDR"}
-kakao_pay = {country = "KR", currency = "KRW"}
-momo = {country = "VN", currency = "VND"}
-gcash = {country = "PH", currency = "PHP"}
-online_banking_fpx = {country = "MY", currency = "MYR"}
-online_banking_thailand = {country = "TH", currency = "THB"}
-touch_n_go = {country = "MY", currency = "MYR"}
-atome = {country = "MY,SG", currency = "MYR,SGD"}
-swish = {country = "SE", currency = "SEK"}
-permata_bank_transfer = {country = "ID", currency = "IDR"}
-bca_bank_transfer = {country = "ID", currency = "IDR"}
-bni_va = {country = "ID", currency = "IDR"}
-bri_va = {country = "ID", currency = "IDR"}
-cimb_va = {country = "ID", currency = "IDR"}
-danamon_va = {country = "ID", currency = "IDR"}
-mandiri_va = {country = "ID", currency = "IDR"}
-alfamart = {country = "ID", currency = "IDR"}
-indomaret = {country = "ID", currency = "IDR"}
-open_banking_uk = {country = "GB", currency = "GBP"}
-oxxo = {country = "MX", currency = "MXN"}
-pay_safe_card = {country = "AT,AU,BE,BR,BE,CA,HR,CY,CZ,DK,FI,FR,GE,DE,GI,HU,IS,IE,KW,LV,IE,LI,LT,LU,MT,MX,MD,ME,NL,NZ,NO,PY,PE,PL,PT,RO,SA,RS,SK,SI,ES,SE,CH,TR,AE,GB,US,UY", currency = "EUR,AUD,BRL,CAD,CZK,DKK,GEL,GIP,HUF,KWD,CHF,MXN,MDL,NZD,NOK,PYG,PEN,PLN,RON,SAR,RSD,SEK,TRY,AED,GBP,USD,UYU"}
-seven_eleven = {country = "JP", currency = "JPY"}
-lawson = {country = "JP", currency = "JPY"}
-mini_stop = {country = "JP", currency = "JPY"}
-family_mart = {country = "JP", currency = "JPY"}
-seicomart = {country = "JP", currency = "JPY"}
-pay_easy = {country = "JP", currency = "JPY"}
+blik = { country = "PL", currency = "PLN" }
+trustly = { country = "ES,GB,SE,NO,AT,NL,DE,DK,FI,EE,LT,LV", currency = "CZK,DKK,EUR,GBP,NOK,SEK" }
+online_banking_czech_republic = { country = "CZ", currency = "EUR,CZK" }
+online_banking_finland = { country = "FI", currency = "EUR" }
+online_banking_poland = { country = "PL", currency = "PLN" }
+online_banking_slovakia = { country = "SK", currency = "EUR,CZK" }
+bancontact_card = { country = "BE", currency = "EUR" }
+ach = { country = "US", currency = "USD" }
+bacs = { country = "GB", currency = "GBP" }
+sepa = { country = "ES,SK,AT,NL,DE,BE,FR,FI,PT,IE,EE,LT,LV,IT", currency = "EUR" }
+ali_pay_hk = { country = "HK", currency = "HKD" }
+bizum = { country = "ES", currency = "EUR" }
+go_pay = { country = "ID", currency = "IDR" }
+kakao_pay = { country = "KR", currency = "KRW" }
+momo = { country = "VN", currency = "VND" }
+gcash = { country = "PH", currency = "PHP" }
+online_banking_fpx = { country = "MY", currency = "MYR" }
+online_banking_thailand = { country = "TH", currency = "THB" }
+touch_n_go = { country = "MY", currency = "MYR" }
+atome = { country = "MY,SG", currency = "MYR,SGD" }
+swish = { country = "SE", currency = "SEK" }
+permata_bank_transfer = { country = "ID", currency = "IDR" }
+bca_bank_transfer = { country = "ID", currency = "IDR" }
+bni_va = { country = "ID", currency = "IDR" }
+bri_va = { country = "ID", currency = "IDR" }
+cimb_va = { country = "ID", currency = "IDR" }
+danamon_va = { country = "ID", currency = "IDR" }
+mandiri_va = { country = "ID", currency = "IDR" }
+alfamart = { country = "ID", currency = "IDR" }
+indomaret = { country = "ID", currency = "IDR" }
+open_banking_uk = { country = "GB", currency = "GBP" }
+oxxo = { country = "MX", currency = "MXN" }
+pay_safe_card = { country = "AT,AU,BE,BR,BE,CA,HR,CY,CZ,DK,FI,FR,GE,DE,GI,HU,IS,IE,KW,LV,IE,LI,LT,LU,MT,MX,MD,ME,NL,NZ,NO,PY,PE,PL,PT,RO,SA,RS,SK,SI,ES,SE,CH,TR,AE,GB,US,UY", currency = "EUR,AUD,BRL,CAD,CZK,DKK,GEL,GIP,HUF,KWD,CHF,MXN,MDL,NZD,NOK,PYG,PEN,PLN,RON,SAR,RSD,SEK,TRY,AED,GBP,USD,UYU" }
+seven_eleven = { country = "JP", currency = "JPY" }
+lawson = { country = "JP", currency = "JPY" }
+mini_stop = { country = "JP", currency = "JPY" }
+family_mart = { country = "JP", currency = "JPY" }
+seicomart = { country = "JP", currency = "JPY" }
+pay_easy = { country = "JP", currency = "JPY" }
pix = { country = "BR", currency = "BRL" }
boleto = { country = "BR", currency = "BRL" }
@@ -443,21 +443,21 @@ debit = { currency = "USD" }
stripe = { long_lived_token = false, payment_method = "wallet", payment_method_type = { type = "disable_only", list = "google_pay" } }
checkout = { long_lived_token = false, payment_method = "wallet", apple_pay_pre_decrypt_flow = "network_tokenization" }
stax = { long_lived_token = true, payment_method = "card,bank_debit" }
-mollie = {long_lived_token = false, payment_method = "card"}
-square = {long_lived_token = false, payment_method = "card"}
+mollie = { long_lived_token = false, payment_method = "card" }
+square = { long_lived_token = false, payment_method = "card" }
braintree = { long_lived_token = false, payment_method = "card" }
-payme = {long_lived_token = false, payment_method = "card"}
-gocardless = {long_lived_token = true, payment_method = "bank_debit"}
+payme = { long_lived_token = false, payment_method = "card" }
+gocardless = { long_lived_token = true, payment_method = "bank_debit" }
[temp_locker_enable_config]
-stripe = {payment_method = "bank_transfer"}
-nuvei = {payment_method = "card"}
-shift4 = {payment_method = "card"}
-bluesnap = {payment_method = "card"}
-bankofamerica = {payment_method = "card"}
-cybersource = {payment_method = "card"}
-nmi = {payment_method = "card"}
-payme = {payment_method = "card"}
+stripe = { payment_method = "bank_transfer" }
+nuvei = { payment_method = "card" }
+shift4 = { payment_method = "card" }
+bluesnap = { payment_method = "card" }
+bankofamerica = { payment_method = "card" }
+cybersource = { payment_method = "card" }
+nmi = { payment_method = "card" }
+payme = { payment_method = "card" }
[connector_customer]
connector_list = "gocardless,stax,stripe"
@@ -496,16 +496,16 @@ wallet.apple_pay = { connector_list = "stripe,adyen,cybersource,noon" }
wallet.paypal = { connector_list = "adyen" }
card.credit = { connector_list = "stripe,adyen,authorizedotnet,cybersource,globalpay,worldpay,multisafepay,nmi,nexinets,noon" }
card.debit = { connector_list = "stripe,adyen,authorizedotnet,cybersource,globalpay,worldpay,multisafepay,nmi,nexinets,noon" }
-bank_debit.ach = { connector_list = "gocardless"}
-bank_debit.becs = { connector_list = "gocardless"}
-bank_debit.sepa = { connector_list = "gocardless"}
-bank_redirect.ideal = {connector_list = "stripe,adyen,globalpay"}
-bank_redirect.sofort = {connector_list = "stripe,adyen,globalpay"}
-bank_redirect.giropay = {connector_list = "adyen,globalpay"}
+bank_debit.ach = { connector_list = "gocardless" }
+bank_debit.becs = { connector_list = "gocardless" }
+bank_debit.sepa = { connector_list = "gocardless" }
+bank_redirect.ideal = { connector_list = "stripe,adyen,globalpay" }
+bank_redirect.sofort = { connector_list = "stripe,adyen,globalpay" }
+bank_redirect.giropay = { connector_list = "adyen,globalpay" }
[mandates.update_mandate_supported]
-card.credit ={connector_list ="cybersource"}
-card.debit = {connector_list ="cybersource"}
+card.credit = { connector_list = "cybersource" }
+card.debit = { connector_list = "cybersource" }
[connector_request_reference_id_config]
merchant_ids_send_payment_id_as_connector_request_id = []
@@ -530,7 +530,7 @@ redis_expiry = 900
pm_auth_key = "Some_pm_auth_key"
[lock_settings]
-redis_lock_expiry_seconds = 180 # 3 * 60 seconds
+redis_lock_expiry_seconds = 180 # 3 * 60 seconds
delay_between_retries_in_milliseconds = 500
[kv_config]
@@ -582,3 +582,17 @@ file_storage_backend = "file_system"
[unmasked_headers]
keys = "user-agent"
+
+[opensearch]
+host = "https://localhost:9200"
+
+[opensearch.auth]
+auth = "basic"
+username = "admin"
+password = "admin"
+region = "eu-central-1"
+
+[opensearch.indexes]
+payment_attempts = "hyperswitch-payment-attempt-events"
+payment_intents = "hyperswitch-payment-intent-events"
+refunds = "hyperswitch-refund-events"
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index 2f94d69790b..4d1731b53ff 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -15,7 +15,7 @@ level = "DEBUG" # What you see in your terminal.
[log.telemetry]
traces_enabled = false # Whether traces are enabled.
-metrics_enabled = true # Whether metrics are enabled.
+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
@@ -244,21 +244,21 @@ workers = 1
[tokenization]
stripe = { long_lived_token = false, payment_method = "wallet", payment_method_type = { type = "disable_only", list = "google_pay" } }
checkout = { long_lived_token = false, payment_method = "wallet", apple_pay_pre_decrypt_flow = "network_tokenization" }
-mollie = {long_lived_token = false, payment_method = "card"}
+mollie = { long_lived_token = false, payment_method = "card" }
stax = { long_lived_token = true, payment_method = "card,bank_debit" }
-square = {long_lived_token = false, payment_method = "card"}
+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"}
+gocardless = { long_lived_token = true, payment_method = "bank_debit" }
[temp_locker_enable_config]
-stripe = {payment_method = "bank_transfer"}
-nuvei = {payment_method = "card"}
-shift4 = {payment_method = "card"}
-bluesnap = {payment_method = "card"}
-bankofamerica = {payment_method = "card"}
-cybersource = {payment_method = "card"}
-nmi = {payment_method = "card"}
-payme = {payment_method = "card"}
+stripe = { payment_method = "bank_transfer" }
+nuvei = { payment_method = "card" }
+shift4 = { payment_method = "card" }
+bluesnap = { payment_method = "card" }
+bankofamerica = { payment_method = "card" }
+cybersource = { payment_method = "card" }
+nmi = { payment_method = "card" }
+payme = { payment_method = "card" }
[dummy_connector]
enabled = true
@@ -284,38 +284,38 @@ discord_invite_url = "https://discord.gg/wJZ7DVW8mm"
payout_eligibility = true
[pm_filters.adyen]
-online_banking_fpx = {country = "MY", currency = "MYR"}
-online_banking_thailand = {country = "TH", currency = "THB"}
-touch_n_go = {country = "MY", currency = "MYR"}
-atome = {country = "MY,SG", currency = "MYR,SGD"}
-swish = {country = "SE", currency = "SEK"}
-permata_bank_transfer = {country = "ID", currency = "IDR"}
-bca_bank_transfer = {country = "ID", currency = "IDR"}
-bni_va = {country = "ID", currency = "IDR"}
-bri_va = {country = "ID", currency = "IDR"}
-cimb_va = {country = "ID", currency = "IDR"}
-danamon_va = {country = "ID", currency = "IDR"}
-mandiri_va = {country = "ID", currency = "IDR"}
-alfamart = {country = "ID", currency = "IDR"}
-indomaret = {country = "ID", currency = "IDR"}
-open_banking_uk = {country = "GB", currency = "GBP"}
-oxxo = {country = "MX", currency = "MXN"}
-pay_safe_card = {country = "AT,AU,BE,BR,BE,CA,HR,CY,CZ,DK,FI,FR,GE,DE,GI,HU,IS,IE,KW,LV,IE,LI,LT,LU,MT,MX,MD,ME,NL,NZ,NO,PY,PE,PL,PT,RO,SA,RS,SK,SI,ES,SE,CH,TR,AE,GB,US,UY", currency = "EUR,AUD,BRL,CAD,CZK,DKK,GEL,GIP,HUF,KWD,CHF,MXN,MDL,NZD,NOK,PYG,PEN,PLN,RON,SAR,RSD,SEK,TRY,AED,GBP,USD,UYU"}
-seven_eleven = {country = "JP", currency = "JPY"}
-lawson = {country = "JP", currency = "JPY"}
-mini_stop = {country = "JP", currency = "JPY"}
-family_mart = {country = "JP", currency = "JPY"}
-seicomart = {country = "JP", currency = "JPY"}
-pay_easy = {country = "JP", currency = "JPY"}
+online_banking_fpx = { country = "MY", currency = "MYR" }
+online_banking_thailand = { country = "TH", currency = "THB" }
+touch_n_go = { country = "MY", currency = "MYR" }
+atome = { country = "MY,SG", currency = "MYR,SGD" }
+swish = { country = "SE", currency = "SEK" }
+permata_bank_transfer = { country = "ID", currency = "IDR" }
+bca_bank_transfer = { country = "ID", currency = "IDR" }
+bni_va = { country = "ID", currency = "IDR" }
+bri_va = { country = "ID", currency = "IDR" }
+cimb_va = { country = "ID", currency = "IDR" }
+danamon_va = { country = "ID", currency = "IDR" }
+mandiri_va = { country = "ID", currency = "IDR" }
+alfamart = { country = "ID", currency = "IDR" }
+indomaret = { country = "ID", currency = "IDR" }
+open_banking_uk = { country = "GB", currency = "GBP" }
+oxxo = { country = "MX", currency = "MXN" }
+pay_safe_card = { country = "AT,AU,BE,BR,BE,CA,HR,CY,CZ,DK,FI,FR,GE,DE,GI,HU,IS,IE,KW,LV,IE,LI,LT,LU,MT,MX,MD,ME,NL,NZ,NO,PY,PE,PL,PT,RO,SA,RS,SK,SI,ES,SE,CH,TR,AE,GB,US,UY", currency = "EUR,AUD,BRL,CAD,CZK,DKK,GEL,GIP,HUF,KWD,CHF,MXN,MDL,NZD,NOK,PYG,PEN,PLN,RON,SAR,RSD,SEK,TRY,AED,GBP,USD,UYU" }
+seven_eleven = { country = "JP", currency = "JPY" }
+lawson = { country = "JP", currency = "JPY" }
+mini_stop = { country = "JP", currency = "JPY" }
+family_mart = { country = "JP", currency = "JPY" }
+seicomart = { country = "JP", currency = "JPY" }
+pay_easy = { country = "JP", currency = "JPY" }
boleto = { country = "BR", currency = "BRL" }
ideal = { country = "NL", currency = "EUR" }
-klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NO,PL,PT,RO,ES,SE,CH,NL,GB,US", currency = "AUD,EUR,CAD,CZK,DKK,NOK,PLN,RON,SEK,CHF,GBP,USD"}
+klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NO,PL,PT,RO,ES,SE,CH,NL,GB,US", currency = "AUD,EUR,CAD,CZK,DKK,NOK,PLN,RON,SEK,CHF,GBP,USD" }
paypal = { country = "AU,NZ,CN,JP,HK,MY,TH,KR,PH,ID,AE,KW,BR,ES,GB,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,FI,RO,HR,UA,MT,SI,GI,PT,IE,CZ,EE,LT,LV,IT,PL,IS,CA,US", currency = "AUD,BRL,CAD,CZK,DKK,EUR,HKD,HUF,INR,JPY,MYR,MXN,NZD,NOK,PHP,PLN,RUB,GBP,SGD,SEK,CHF,THB,USD" }
-sofort = { country = "AT,BE,DE,ES,CH,NL", currency = "CHF,EUR"}
+sofort = { country = "AT,BE,DE,ES,CH,NL", currency = "CHF,EUR" }
[pm_filters.volt]
-open_banking_uk = {country = "DE,GB,AT,BE,CY,EE,ES,FI,FR,GR,HR,IE,IT,LT,LU,LV,MT,NL,PT,SI,SK,BG,CZ,DK,HU,NO,PL,RO,SE,AU,BR", currency = "EUR,GBP,DKK,NOK,PLN,SEK,AUD,BRL"}
+open_banking_uk = { country = "DE,GB,AT,BE,CY,EE,ES,FI,FR,GR,HR,IE,IT,LT,LU,LV,MT,NL,PT,SI,SK,BG,CZ,DK,HU,NO,PL,RO,SE,AU,BR", currency = "EUR,GBP,DKK,NOK,PLN,SEK,AUD,BRL" }
[pm_filters.zen]
credit = { not_available_flows = { capture_method = "manual" } }
@@ -330,7 +330,7 @@ red_compra = { country = "CL", currency = "CLP" }
red_pagos = { country = "UY", currency = "UYU" }
[pm_filters.stripe]
-cashapp = {country = "US", currency = "USD"}
+cashapp = { country = "US", currency = "USD" }
[pm_filters.prophetpay]
card_redirect = { currency = "USD" }
@@ -357,25 +357,25 @@ adyen.banks = "affin_bank,agro_bank,alliance_bank,am_bank,bank_islam,bank_muamal
adyen.banks = "bangkok_bank,krungsri_bank,krung_thai_bank,the_siam_commercial_bank,kasikorn_bank"
[bank_config.open_banking_uk]
-adyen = { banks = "aib,bank_of_scotland,danske_bank,first_direct,first_trust,halifax,lloyds,monzo,nat_west,nationwide_bank,royal_bank_of_scotland,starling,tsb_bank,tesco_bank,ulster_bank,barclays,hsbc_bank,revolut,santander_przelew24,open_bank_success,open_bank_failure,open_bank_cancelled"}
+adyen = { banks = "aib,bank_of_scotland,danske_bank,first_direct,first_trust,halifax,lloyds,monzo,nat_west,nationwide_bank,royal_bank_of_scotland,starling,tsb_bank,tesco_bank,ulster_bank,barclays,hsbc_bank,revolut,santander_przelew24,open_bank_success,open_bank_failure,open_bank_cancelled" }
[mandates.supported_payment_methods]
-pay_later.klarna = {connector_list = "adyen"}
-wallet.google_pay = {connector_list = "stripe,adyen"}
-wallet.apple_pay = {connector_list = "stripe,adyen,cybersource,noon"}
-wallet.paypal = {connector_list = "adyen"}
-card.credit = {connector_list = "stripe,adyen,authorizedotnet,cybersource,globalpay,worldpay,multisafepay,nmi,nexinets,noon"}
-card.debit = {connector_list = "stripe,adyen,authorizedotnet,cybersource,globalpay,worldpay,multisafepay,nmi,nexinets,noon"}
-bank_debit.ach = { connector_list = "gocardless"}
-bank_debit.becs = { connector_list = "gocardless"}
-bank_debit.sepa = { connector_list = "gocardless"}
-bank_redirect.ideal = {connector_list = "stripe,adyen,globalpay"}
-bank_redirect.sofort = {connector_list = "stripe,adyen,globalpay"}
-bank_redirect.giropay = {connector_list = "adyen,globalpay"}
+pay_later.klarna = { connector_list = "adyen" }
+wallet.google_pay = { connector_list = "stripe,adyen" }
+wallet.apple_pay = { connector_list = "stripe,adyen,cybersource,noon" }
+wallet.paypal = { connector_list = "adyen" }
+card.credit = { connector_list = "stripe,adyen,authorizedotnet,cybersource,globalpay,worldpay,multisafepay,nmi,nexinets,noon" }
+card.debit = { connector_list = "stripe,adyen,authorizedotnet,cybersource,globalpay,worldpay,multisafepay,nmi,nexinets,noon" }
+bank_debit.ach = { connector_list = "gocardless" }
+bank_debit.becs = { connector_list = "gocardless" }
+bank_debit.sepa = { connector_list = "gocardless" }
+bank_redirect.ideal = { connector_list = "stripe,adyen,globalpay" }
+bank_redirect.sofort = { connector_list = "stripe,adyen,globalpay" }
+bank_redirect.giropay = { connector_list = "adyen,globalpay" }
[mandates.update_mandate_supported]
-card.credit ={connector_list ="cybersource"}
-card.debit = {connector_list ="cybersource"}
+card.credit = { connector_list = "cybersource" }
+card.debit = { connector_list = "cybersource" }
[connector_customer]
connector_list = "gocardless,stax,stripe"
@@ -389,7 +389,7 @@ redis_expiry = 900
pm_auth_key = "Some_pm_auth_key"
[lock_settings]
-redis_lock_expiry_seconds = 180 # 3 * 60 seconds
+redis_lock_expiry_seconds = 180 # 3 * 60 seconds
delay_between_retries_in_milliseconds = 500
[events.kafka]
@@ -440,4 +440,18 @@ source = "logs"
file_storage_backend = "file_system"
[unmasked_headers]
-keys = "user-agent"
\ No newline at end of file
+keys = "user-agent"
+
+[opensearch]
+host = "https://opensearch:9200"
+
+[opensearch.auth]
+auth = "basic"
+username = "admin"
+password = "admin"
+region = "eu-central-1"
+
+[opensearch.indexes]
+payment_attempts = "hyperswitch-payment-attempt-events"
+payment_intents = "hyperswitch-payment-intent-events"
+refunds = "hyperswitch-refund-events"
\ No newline at end of file
diff --git a/crates/analytics/Cargo.toml b/crates/analytics/Cargo.toml
index f3e01492135..f07e0a94ea5 100644
--- a/crates/analytics/Cargo.toml
+++ b/crates/analytics/Cargo.toml
@@ -1,7 +1,7 @@
[package]
name = "analytics"
version = "0.1.0"
-description = "Analytics / Reports related functionality"
+description = "Analytics / Reports / Search related functionality"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
@@ -9,29 +9,43 @@ edition = "2021"
[dependencies]
# First party crates
-api_models = { version = "0.1.0", path = "../api_models" , features = ["errors"]}
+api_models = { version = "0.1.0", path = "../api_models", features = [
+ "errors",
+] }
storage_impl = { version = "0.1.0", path = "../storage_impl", default-features = false }
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" }
masking = { version = "0.1.0", path = "../masking" }
-router_env = { version = "0.1.0", path = "../router_env", features = ["log_extra_implicit_fields", "log_custom_entries_to_extra"] }
-diesel_models = { version = "0.1.0", path = "../diesel_models", features = ["kv_store"] }
+router_env = { version = "0.1.0", path = "../router_env", features = [
+ "log_extra_implicit_fields",
+ "log_custom_entries_to_extra",
+] }
+diesel_models = { version = "0.1.0", path = "../diesel_models", features = [
+ "kv_store",
+] }
#Third Party dependencies
actix-web = "4.3.1"
async-trait = "0.1.68"
-aws-config = { version = "0.55.3" }
-aws-sdk-lambda = { version = "0.28.0" }
-aws-smithy-types = { version = "0.55.3" }
+aws-config = { version = "1.1.6", features = ["behavior-version-latest"] }
+aws-sdk-lambda = { version = "1.1.4" }
+aws-smithy-types = { version = "1.1.6" }
bigdecimal = { version = "0.3.1", features = ["serde"] }
error-stack = "0.3.1"
futures = "0.3.28"
+opensearch = { version = "2.2.0", features = ["aws-auth"] }
once_cell = "1.18.0"
reqwest = { version = "0.11.18", features = ["serde_json"] }
serde = { version = "1.0.193", features = ["derive", "rc"] }
serde_json = "1.0.108"
-sqlx = { version = "0.6.3", features = ["postgres", "runtime-actix", "runtime-actix-native-tls", "time", "bigdecimal"] }
+sqlx = { version = "0.6.3", features = [
+ "postgres",
+ "runtime-actix",
+ "runtime-actix-native-tls",
+ "time",
+ "bigdecimal",
+] }
strum = { version = "0.25.0", features = ["derive"] }
thiserror = "1.0.43"
time = { version = "0.3.21", features = ["serde", "serde-well-known", "std"] }
diff --git a/crates/analytics/src/lambda_utils.rs b/crates/analytics/src/lambda_utils.rs
index f9446a402b4..4f8320f29b5 100644
--- a/crates/analytics/src/lambda_utils.rs
+++ b/crates/analytics/src/lambda_utils.rs
@@ -1,5 +1,5 @@
-use aws_config::{self, meta::region::RegionProviderChain};
-use aws_sdk_lambda::{config::Region, types::InvocationType::Event, Client};
+use aws_config::{self, meta::region::RegionProviderChain, Region};
+use aws_sdk_lambda::{types::InvocationType::Event, Client};
use aws_smithy_types::Blob;
use common_utils::errors::CustomResult;
use error_stack::{IntoReport, ResultExt};
diff --git a/crates/analytics/src/lib.rs b/crates/analytics/src/lib.rs
index d8de32a732b..68ca51a0df0 100644
--- a/crates/analytics/src/lib.rs
+++ b/crates/analytics/src/lib.rs
@@ -12,6 +12,7 @@ pub mod connector_events;
pub mod health_check;
pub mod outgoing_webhook_event;
pub mod sdk_events;
+pub mod search;
mod sqlx;
mod types;
use api_event::metrics::{ApiEventMetric, ApiEventMetricRow};
@@ -664,3 +665,42 @@ pub struct ReportConfig {
pub dispute_function: String,
pub region: String,
}
+
+#[derive(Clone, Debug, serde::Deserialize)]
+#[serde(tag = "auth")]
+#[serde(rename_all = "lowercase")]
+pub enum OpensearchAuth {
+ Basic { username: String, password: String },
+ Aws { region: String },
+}
+
+#[derive(Clone, Debug, serde::Deserialize)]
+pub struct OpensearchIndexes {
+ pub payment_attempts: String,
+ pub payment_intents: String,
+ pub refunds: String,
+}
+
+#[derive(Clone, Debug, serde::Deserialize)]
+pub struct OpensearchConfig {
+ host: String,
+ auth: OpensearchAuth,
+ indexes: OpensearchIndexes,
+}
+
+impl Default for OpensearchConfig {
+ fn default() -> Self {
+ Self {
+ host: "https://localhost:9200".to_string(),
+ auth: OpensearchAuth::Basic {
+ username: "admin".to_string(),
+ password: "admin".to_string(),
+ },
+ indexes: OpensearchIndexes {
+ payment_attempts: "hyperswitch-payment-attempt-events".to_string(),
+ payment_intents: "hyperswitch-payment-intent-events".to_string(),
+ refunds: "hyperswitch-refund-events".to_string(),
+ },
+ }
+ }
+}
diff --git a/crates/analytics/src/search.rs b/crates/analytics/src/search.rs
new file mode 100644
index 00000000000..8637c9d1105
--- /dev/null
+++ b/crates/analytics/src/search.rs
@@ -0,0 +1,150 @@
+use api_models::analytics::search::{
+ GetGlobalSearchRequest, GetSearchRequestWithIndex, GetSearchResponse, OpenMsearchOutput,
+ OpensearchOutput, SearchIndex,
+};
+use aws_config::{self, meta::region::RegionProviderChain, Region};
+use common_utils::errors::CustomResult;
+use opensearch::{
+ auth::Credentials,
+ cert::CertificateValidation,
+ http::{
+ request::JsonBody,
+ transport::{SingleNodeConnectionPool, TransportBuilder},
+ Url,
+ },
+ MsearchParts, OpenSearch, SearchParts,
+};
+use serde_json::{json, Value};
+use strum::IntoEnumIterator;
+
+use crate::{errors::AnalyticsError, OpensearchAuth, OpensearchConfig, OpensearchIndexes};
+
+#[derive(Debug, thiserror::Error)]
+pub enum OpensearchError {
+ #[error("Opensearch connection error")]
+ ConnectionError,
+ #[error("Opensearch NON-200 response content: '{0}'")]
+ ResponseNotOK(String),
+ #[error("Opensearch response error")]
+ ResponseError,
+}
+
+pub fn search_index_to_opensearch_index(index: SearchIndex, config: &OpensearchIndexes) -> String {
+ match index {
+ SearchIndex::PaymentAttempts => config.payment_attempts.clone(),
+ SearchIndex::PaymentIntents => config.payment_intents.clone(),
+ SearchIndex::Refunds => config.refunds.clone(),
+ }
+}
+
+async fn get_opensearch_client(config: OpensearchConfig) -> Result<OpenSearch, OpensearchError> {
+ let url = Url::parse(&config.host).map_err(|_| OpensearchError::ConnectionError)?;
+ let transport = match config.auth {
+ OpensearchAuth::Basic { username, password } => {
+ let credentials = Credentials::Basic(username, password);
+ TransportBuilder::new(SingleNodeConnectionPool::new(url))
+ .cert_validation(CertificateValidation::None)
+ .auth(credentials)
+ .build()
+ .map_err(|_| OpensearchError::ConnectionError)?
+ }
+ OpensearchAuth::Aws { region } => {
+ let region_provider = RegionProviderChain::first_try(Region::new(region));
+ let sdk_config = aws_config::from_env().region(region_provider).load().await;
+ let conn_pool = SingleNodeConnectionPool::new(url);
+ TransportBuilder::new(conn_pool)
+ .auth(
+ sdk_config
+ .clone()
+ .try_into()
+ .map_err(|_| OpensearchError::ConnectionError)?,
+ )
+ .service_name("es")
+ .build()
+ .map_err(|_| OpensearchError::ConnectionError)?
+ }
+ };
+ Ok(OpenSearch::new(transport))
+}
+
+pub async fn msearch_results(
+ req: GetGlobalSearchRequest,
+ merchant_id: &String,
+ config: OpensearchConfig,
+) -> CustomResult<Vec<GetSearchResponse>, AnalyticsError> {
+ let client = get_opensearch_client(config.clone())
+ .await
+ .map_err(|_| AnalyticsError::UnknownError)?;
+
+ let mut msearch_vector: Vec<JsonBody<Value>> = vec![];
+ for index in SearchIndex::iter() {
+ msearch_vector
+ .push(json!({"index": search_index_to_opensearch_index(index,&config.indexes)}).into());
+ msearch_vector.push(json!({"query": {"bool": {"must": {"query_string": {"query": req.query}}, "filter": {"match_phrase": {"merchant_id": merchant_id}}}}}).into());
+ }
+
+ let response = client
+ .msearch(MsearchParts::None)
+ .body(msearch_vector)
+ .send()
+ .await
+ .map_err(|_| AnalyticsError::UnknownError)?;
+
+ let response_body = response
+ .json::<OpenMsearchOutput<Value>>()
+ .await
+ .map_err(|_| AnalyticsError::UnknownError)?;
+
+ 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(),
+ })
+ .collect())
+}
+
+pub async fn search_results(
+ req: GetSearchRequestWithIndex,
+ merchant_id: &String,
+ config: OpensearchConfig,
+) -> CustomResult<GetSearchResponse, AnalyticsError> {
+ let search_req = req.search_req;
+
+ let client = get_opensearch_client(config.clone())
+ .await
+ .map_err(|_| AnalyticsError::UnknownError)?;
+
+ let response = client
+ .search(SearchParts::Index(&[&search_index_to_opensearch_index(req.index.clone(),&config.indexes)]))
+ .from(search_req.offset)
+ .size(search_req.count)
+ .body(json!({"query": {"bool": {"must": {"query_string": {"query": search_req.query}}, "filter": {"match_phrase": {"merchant_id": merchant_id}}}}}))
+ .send()
+ .await
+ .map_err(|_| AnalyticsError::UnknownError)?;
+
+ let response_body = response
+ .json::<OpensearchOutput<Value>>()
+ .await
+ .map_err(|_| AnalyticsError::UnknownError)?;
+
+ Ok(GetSearchResponse {
+ count: response_body.hits.total.value,
+ index: req.index,
+ hits: response_body
+ .hits
+ .hits
+ .into_iter()
+ .map(|hit| hit._source)
+ .collect(),
+ })
+}
diff --git a/crates/api_models/src/analytics.rs b/crates/api_models/src/analytics.rs
index 1434c357798..ad035c707cc 100644
--- a/crates/api_models/src/analytics.rs
+++ b/crates/api_models/src/analytics.rs
@@ -19,6 +19,7 @@ pub mod outgoing_webhook_event;
pub mod payments;
pub mod refunds;
pub mod sdk_events;
+pub mod search;
#[derive(Debug, serde::Serialize)]
pub struct NameDescription {
@@ -251,7 +252,6 @@ pub struct GetApiEventMetricRequest {
#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "camelCase")]
-
pub struct GetDisputeFilterRequest {
pub time_range: TimeRange,
#[serde(default)]
diff --git a/crates/api_models/src/analytics/search.rs b/crates/api_models/src/analytics/search.rs
new file mode 100644
index 00000000000..07223c90660
--- /dev/null
+++ b/crates/api_models/src/analytics/search.rs
@@ -0,0 +1,73 @@
+use serde_json::Value;
+
+#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)]
+pub struct SearchFilters {
+ pub payment_method: Option<Vec<String>>,
+}
+
+#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct GetGlobalSearchRequest {
+ pub query: String,
+ #[serde(default)]
+ pub filters: Option<SearchFilters>,
+}
+
+#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct GetSearchRequest {
+ pub offset: i64,
+ pub count: i64,
+ pub query: String,
+ #[serde(default)]
+ pub filters: Option<SearchFilters>,
+}
+
+#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct GetSearchRequestWithIndex {
+ pub index: SearchIndex,
+ pub search_req: GetSearchRequest,
+}
+
+#[derive(Debug, strum::EnumIter, Clone, serde::Deserialize, serde::Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum SearchIndex {
+ PaymentAttempts,
+ PaymentIntents,
+ Refunds,
+}
+
+#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct GetSearchResponse {
+ pub count: u64,
+ pub index: SearchIndex,
+ pub hits: Vec<Value>,
+}
+
+#[derive(Debug, serde::Deserialize)]
+pub struct OpenMsearchOutput<T> {
+ pub responses: Vec<OpensearchOutput<T>>,
+}
+
+#[derive(Debug, serde::Deserialize)]
+pub struct OpensearchOutput<T> {
+ pub hits: OpensearchResults<T>,
+}
+
+#[derive(Debug, serde::Deserialize)]
+pub struct OpensearchResults<T> {
+ pub total: OpensearchResultsTotal,
+ pub hits: Vec<OpensearchHits<T>>,
+}
+
+#[derive(Debug, serde::Deserialize)]
+pub struct OpensearchResultsTotal {
+ pub value: u64,
+}
+
+#[derive(Debug, serde::Deserialize)]
+pub struct OpensearchHits<T> {
+ pub _source: T,
+}
diff --git a/crates/api_models/src/events.rs b/crates/api_models/src/events.rs
index 218881389db..46fa8caa6df 100644
--- a/crates/api_models/src/events.rs
+++ b/crates/api_models/src/events.rs
@@ -23,7 +23,7 @@ use crate::{
admin::*,
analytics::{
api_event::*, connector_events::ConnectorEventsRequest,
- outgoing_webhook_event::OutgoingWebhookLogsRequest, sdk_events::*, *,
+ outgoing_webhook_event::OutgoingWebhookLogsRequest, sdk_events::*, search::*, *,
},
api_keys::*,
cards_info::*,
@@ -96,6 +96,10 @@ impl_misc_api_event_type!(
ReportRequest,
ConnectorEventsRequest,
OutgoingWebhookLogsRequest,
+ GetGlobalSearchRequest,
+ GetSearchRequest,
+ GetSearchResponse,
+ GetSearchRequestWithIndex,
GetDisputeFilterRequest,
DisputeFiltersResponse,
GetDisputeMetricRequest
diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs
index f7bee88b8c3..a9c2b8995b5 100644
--- a/crates/router/src/analytics.rs
+++ b/crates/router/src/analytics.rs
@@ -8,6 +8,9 @@ pub mod routes {
outgoing_webhook_event::outgoing_webhook_events_core, sdk_events::sdk_events_core,
};
use api_models::analytics::{
+ search::{
+ GetGlobalSearchRequest, GetSearchRequest, GetSearchRequestWithIndex, SearchIndex,
+ },
GenerateReportRequest, GetApiEventFiltersRequest, GetApiEventMetricRequest,
GetDisputeMetricRequest, GetPaymentFiltersRequest, GetPaymentMetricRequest,
GetRefundFilterRequest, GetRefundMetricRequest, GetSdkEventFiltersRequest,
@@ -89,6 +92,12 @@ pub mod routes {
web::resource("metrics/api_events")
.route(web::post().to(get_api_events_metrics)),
)
+ .service(
+ web::resource("search").route(web::post().to(get_global_search_results)),
+ )
+ .service(
+ web::resource("search/{domain}").route(web::post().to(get_search_results)),
+ )
.service(
web::resource("filters/disputes")
.route(web::post().to(get_dispute_filters)),
@@ -113,7 +122,7 @@ pub mod routes {
state,
&req,
domain.into_inner(),
- |_, _, domain| async {
+ |_, _, domain: analytics::AnalyticsDomain| async {
analytics::core::get_domain_info(domain)
.await
.map(ApplicationResponse::Json)
@@ -592,6 +601,63 @@ pub mod routes {
.await
}
+ pub async fn get_global_search_results(
+ state: web::Data<AppState>,
+ req: actix_web::HttpRequest,
+ json_payload: web::Json<GetGlobalSearchRequest>,
+ ) -> impl Responder {
+ let flow = AnalyticsFlow::GetGlobalSearchResults;
+ Box::pin(api::server_wrap(
+ flow,
+ state.clone(),
+ &req,
+ json_payload.into_inner(),
+ |state, auth: AuthenticationData, req| async move {
+ analytics::search::msearch_results(
+ req,
+ &auth.merchant_account.merchant_id,
+ state.conf.opensearch.clone(),
+ )
+ .await
+ .map(ApplicationResponse::Json)
+ },
+ &auth::JWTAuth(Permission::Analytics),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+ }
+
+ pub async fn get_search_results(
+ state: web::Data<AppState>,
+ req: actix_web::HttpRequest,
+ json_payload: web::Json<GetSearchRequest>,
+ index: actix_web::web::Path<SearchIndex>,
+ ) -> impl Responder {
+ let flow = AnalyticsFlow::GetSearchResults;
+ let indexed_req = GetSearchRequestWithIndex {
+ search_req: json_payload.into_inner(),
+ index: index.into_inner(),
+ };
+ Box::pin(api::server_wrap(
+ flow,
+ state.clone(),
+ &req,
+ indexed_req,
+ |state, auth: AuthenticationData, req| async move {
+ analytics::search::search_results(
+ req,
+ &auth.merchant_account.merchant_id,
+ state.conf.opensearch.clone(),
+ )
+ .await
+ .map(ApplicationResponse::Json)
+ },
+ &auth::JWTAuth(Permission::Analytics),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+ }
+
pub async fn get_dispute_filters(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rs
index f89d1811988..6906b5a3e7a 100644
--- a/crates/router/src/configs/secrets_transformers.rs
+++ b/crates/router/src/configs/secrets_transformers.rs
@@ -350,6 +350,8 @@ pub(crate) async fn fetch_raw_secrets(
payment_link: conf.payment_link,
#[cfg(feature = "olap")]
analytics,
+ #[cfg(feature = "olap")]
+ opensearch: conf.opensearch,
#[cfg(feature = "kv_store")]
kv_config: conf.kv_config,
#[cfg(feature = "frm")]
diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs
index dc4826dfed6..2f87c5c21d7 100644
--- a/crates/router/src/configs/settings.rs
+++ b/crates/router/src/configs/settings.rs
@@ -4,7 +4,7 @@ use std::{
};
#[cfg(feature = "olap")]
-use analytics::ReportConfig;
+use analytics::{OpensearchConfig, ReportConfig};
use api_models::{enums, payment_methods::RequiredFieldInfo};
use common_utils::ext_traits::ConfigExt;
use config::{Environment, File};
@@ -112,6 +112,8 @@ pub struct Settings<S: SecretState> {
pub frm: Frm,
#[cfg(feature = "olap")]
pub report_download_config: ReportConfig,
+ #[cfg(feature = "olap")]
+ pub opensearch: OpensearchConfig,
pub events: EventsConfig,
#[cfg(feature = "olap")]
pub connector_onboarding: SecretStateContainer<ConnectorOnboarding, S>,
diff --git a/crates/router_env/src/lib.rs b/crates/router_env/src/lib.rs
index b68cdcc6fcc..5ad0f706706 100644
--- a/crates/router_env/src/lib.rs
+++ b/crates/router_env/src/lib.rs
@@ -54,6 +54,8 @@ pub enum AnalyticsFlow {
GetApiEventFilters,
GetConnectorEvents,
GetOutgoingWebhookEvents,
+ GetGlobalSearchResults,
+ GetSearchResults,
GetDisputeFilters,
GetDisputeMetrics,
}
|
2024-02-26T20:52:19Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
Search APIs for dashboard global search
### 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`
-->
## Motivation and Context
Search APIs for dashboard global search
## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
45ed56f16516c44acbe75b75c0621b78ccdb9894
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4000
|
Bug: fix: revert mget use authorization
In the hosted environment, where we have multiple redis clusters `mget` is not working as expected and throwing the following error: `Unknown Error: CROSSSLOT Keys in request don't hash to the same slot`.
Temporary fix is to revert the PR which is using `mget`
|
diff --git a/crates/router/src/services/authentication/blacklist.rs b/crates/router/src/services/authentication/blacklist.rs
index b5cdcaf0840..2ee8302be63 100644
--- a/crates/router/src/services/authentication/blacklist.rs
+++ b/crates/router/src/services/authentication/blacklist.rs
@@ -80,25 +80,19 @@ pub async fn check_user_in_blacklist<A: AppStateInfo>(
.map(|timestamp| timestamp.map_or(false, |timestamp| timestamp > token_issued_at))
}
-pub async fn check_user_and_role_in_blacklist<A: AppStateInfo>(
+pub async fn check_role_in_blacklist<A: AppStateInfo>(
state: &A,
- user_id: &str,
role_id: &str,
token_expiry: u64,
) -> RouterResult<bool> {
- let user_token = format!("{}{}", USER_BLACKLIST_PREFIX, user_id);
- let role_token = format!("{}{}", ROLE_BLACKLIST_PREFIX, role_id);
+ let token = format!("{}{}", ROLE_BLACKLIST_PREFIX, role_id);
let token_issued_at = expiry_to_i64(token_expiry - JWT_TOKEN_TIME_IN_SECS)?;
let redis_conn = get_redis_connection(state)?;
-
- Ok(redis_conn
- .get_multiple_keys::<Vec<&str>, i64>(vec![user_token.as_str(), role_token.as_str()])
+ redis_conn
+ .get_key::<Option<i64>>(token.as_str())
.await
- .change_context(ApiErrorResponse::InternalServerError)?
- .into_iter()
- .max()
- .flatten()
- .map_or(false, |timestamp| timestamp > token_issued_at))
+ .change_context(ApiErrorResponse::InternalServerError)
+ .map(|timestamp| timestamp.map_or(false, |timestamp| timestamp > token_issued_at))
}
#[cfg(feature = "email")]
@@ -156,7 +150,10 @@ impl BlackList for AuthToken {
where
A: AppStateInfo + Sync,
{
- check_user_and_role_in_blacklist(state, &self.user_id, &self.role_id, self.exp).await
+ Ok(
+ check_user_in_blacklist(state, &self.user_id, self.exp).await?
+ || check_role_in_blacklist(state, &self.role_id, self.exp).await?,
+ )
}
}
|
2024-03-07T07:29:36Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
`mget` is not working in the hosted version. So, this PR will revert the #3945 which uses `mget``.
### 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 #4000
## How did you test it?
Authentication and authorization should work as expected.
1. Signin with any user
```
curl --location 'http://localhost:8080/user/signin' \
--header 'Content-Type: application/json' \
--data-raw '{
"email": "user email",
"password": "password"
}'
```
Response:
```
{
"token": JWT,
"merchant_id": "merchant_id",
"name": "user name"
"email": "user email",
"verification_days_left": null,
"user_role": "org_admin"
}
```
2. Try to hit any api which uses token.
```
curl --location 'http://localhost:8080/user/role/list?groups=true' \
--header 'Authorization: Bearer JWT'
```
Response:
```
[
{
"role_id": "merchant_view_only",
"groups": [
"operations_view",
"connectors_view",
"workflows_view",
"analytics_view",
"users_view",
"merchant_details_view"
],
"role_name": "view_only",
"role_scope": "organization"
},
{
"role_id": "merchant_operator",
"groups": [
"operations_view",
"operations_manage",
"connectors_view",
"workflows_view",
"analytics_view",
"users_view",
"merchant_details_view"
],
"role_name": "operator",
"role_scope": "organization"
},
{
"role_id": "merchant_admin",
"groups": [
"operations_view",
"operations_manage",
"connectors_view",
"connectors_manage",
"workflows_view",
"workflows_manage",
"analytics_view",
"users_view",
"users_manage",
"merchant_details_view",
"merchant_details_manage"
],
"role_name": "admin",
"role_scope": "organization"
},
{
"role_id": "merchant_iam_admin",
"groups": [
"operations_view",
"analytics_view",
"users_view",
"users_manage",
"merchant_details_view"
],
"role_name": "iam",
"role_scope": "organization"
},
{
"role_id": "merchant_developer",
"groups": [
"operations_view",
"connectors_view",
"analytics_view",
"users_view",
"merchant_details_view",
"merchant_details_manage"
],
"role_name": "developer",
"role_scope": "organization"
},
{
"role_id": "merchant_customer_support",
"groups": [
"operations_view",
"analytics_view",
"users_view",
"merchant_details_view"
],
"role_name": "customer_support",
"role_scope": "organization"
}
]
```
## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
6671bff3b11e9548a0085046d2594cad9f2571e2
|
|
juspay/hyperswitch
|
juspay__hyperswitch-3998
|
Bug: Creating a domain config (ENV) - `nrid_supported_connectors`
Create a application level config (`nrid_supported_connectors`) that contains the list of connectors that supports pg agnostic MITs,
|
diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml
index 77040f79a4a..67dfddd0d55 100644
--- a/config/deployments/integration_test.toml
+++ b/config/deployments/integration_test.toml
@@ -129,6 +129,9 @@ bank_redirect.giropay.connector_list = "adyen,globalpay"
card.credit ={connector_list ="cybersource"}
card.debit = {connector_list ="cybersource"}
+[network_transaction_id_supported_connectors]
+connector_list = "stripe,adyen,cybersource"
+
[multiple_api_version_supported_connectors]
supported_connectors = "braintree"
diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml
index 8ae12dc54a6..03dc7825222 100644
--- a/config/deployments/sandbox.toml
+++ b/config/deployments/sandbox.toml
@@ -128,6 +128,9 @@ bank_redirect.giropay.connector_list = "adyen,globalpay"
card.credit = { connector_list = "cybersource" }
card.debit = { connector_list = "cybersource" }
+[network_transaction_id_supported_connectors]
+connector_list = "stripe,adyen,cybersource"
+
[multiple_api_version_supported_connectors]
supported_connectors = "braintree"
diff --git a/config/development.toml b/config/development.toml
index 8ba5c076071..5cdd5f0b9bf 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -511,6 +511,9 @@ bank_redirect.giropay = { connector_list = "adyen,globalpay" }
card.credit = { connector_list = "cybersource" }
card.debit = { connector_list = "cybersource" }
+[network_transaction_id_supported_connectors]
+connector_list = "stripe,adyen,cybersource"
+
[connector_request_reference_id_config]
merchant_ids_send_payment_id_as_connector_request_id = []
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index eb32b47e3b4..1077bf34c02 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -381,6 +381,9 @@ bank_redirect.giropay = { connector_list = "adyen,globalpay" }
card.credit = { connector_list = "cybersource" }
card.debit = { connector_list = "cybersource" }
+[network_transaction_id_supported_connectors]
+connector_list = "stripe,adyen,cybersource"
+
[connector_customer]
connector_list = "gocardless,stax,stripe"
payout_connector_list = "wise"
diff --git a/crates/diesel_models/src/payment_method.rs b/crates/diesel_models/src/payment_method.rs
index ef153c23a7b..681a57bda87 100644
--- a/crates/diesel_models/src/payment_method.rs
+++ b/crates/diesel_models/src/payment_method.rs
@@ -38,6 +38,7 @@ pub struct PaymentMethod {
pub connector_mandate_details: Option<serde_json::Value>,
pub customer_acceptance: Option<pii::SecretSerdeValue>,
pub status: storage_enums::PaymentMethodStatus,
+ pub network_transaction_id: Option<String>,
}
#[derive(Clone, Debug, Eq, PartialEq, Insertable, router_derive::DebugAsDisplay)]
@@ -69,6 +70,7 @@ pub struct PaymentMethodNew {
pub connector_mandate_details: Option<serde_json::Value>,
pub customer_acceptance: Option<pii::SecretSerdeValue>,
pub status: storage_enums::PaymentMethodStatus,
+ pub network_transaction_id: Option<String>,
}
impl Default for PaymentMethodNew {
@@ -102,6 +104,7 @@ impl Default for PaymentMethodNew {
connector_mandate_details: Option::default(),
customer_acceptance: Option::default(),
status: storage_enums::PaymentMethodStatus::Active,
+ network_transaction_id: Option::default(),
}
}
}
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index 8e8bf48a538..ad30609a770 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -913,6 +913,8 @@ diesel::table! {
customer_acceptance -> Nullable<Jsonb>,
#[max_length = 64]
status -> Varchar,
+ #[max_length = 255]
+ network_transaction_id -> Nullable<Varchar>,
}
}
diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rs
index 6906b5a3e7a..537f6666c5d 100644
--- a/crates/router/src/configs/secrets_transformers.rs
+++ b/crates/router/src/configs/secrets_transformers.rs
@@ -335,6 +335,8 @@ pub(crate) async fn fetch_raw_secrets(
#[cfg(feature = "email")]
email: conf.email,
mandates: conf.mandates,
+ network_transaction_id_supported_connectors: conf
+ .network_transaction_id_supported_connectors,
required_fields: conf.required_fields,
delayed_session_response: conf.delayed_session_response,
webhook_source_verification_call: conf.webhook_source_verification_call,
diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs
index d92812cee40..a0dce991295 100644
--- a/crates/router/src/configs/settings.rs
+++ b/crates/router/src/configs/settings.rs
@@ -91,6 +91,7 @@ pub struct Settings<S: SecretState> {
pub email: EmailSettings,
pub cors: CorsSettings,
pub mandates: Mandates,
+ pub network_transaction_id_supported_connectors: NetworkTransactionIdSupportedConnectors,
pub required_fields: RequiredFields,
pub delayed_session_response: DelayedSessionConfig,
pub webhook_source_verification_call: WebhookSourceVerificationCall,
@@ -251,6 +252,12 @@ pub struct Mandates {
pub update_mandate_supported: SupportedPaymentMethodsForMandate,
}
+#[derive(Debug, Deserialize, Clone, Default)]
+pub struct NetworkTransactionIdSupportedConnectors {
+ #[serde(deserialize_with = "deserialize_hashset")]
+ pub connector_list: HashSet<api_models::enums::Connector>,
+}
+
#[derive(Debug, Deserialize, Clone)]
pub struct SupportedPaymentMethodsForMandate(
pub HashMap<enums::PaymentMethod, SupportedPaymentMethodTypesForMandate>,
diff --git a/crates/router/src/db/payment_method.rs b/crates/router/src/db/payment_method.rs
index 14f650127dd..188eeeddc10 100644
--- a/crates/router/src/db/payment_method.rs
+++ b/crates/router/src/db/payment_method.rs
@@ -275,6 +275,7 @@ impl PaymentMethodInterface for MockDb {
connector_mandate_details: payment_method_new.connector_mandate_details,
customer_acceptance: payment_method_new.customer_acceptance,
status: payment_method_new.status,
+ network_transaction_id: payment_method_new.network_transaction_id,
};
payment_methods.push(payment_method.clone());
Ok(payment_method)
diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml
index 72eb6f25559..a2d2648133b 100644
--- a/loadtest/config/development.toml
+++ b/loadtest/config/development.toml
@@ -277,6 +277,9 @@ wildcard_origin = false
card.credit ={connector_list ="cybersource"}
card.debit = {connector_list ="cybersource"}
+[network_transaction_id_supported_connectors]
+connector_list = "stripe,adyen,cybersource"
+
[analytics]
source = "sqlx"
diff --git a/migrations/2024-03-07-102620_add-network-transaction-id/down.sql b/migrations/2024-03-07-102620_add-network-transaction-id/down.sql
new file mode 100644
index 00000000000..4cf99815a9b
--- /dev/null
+++ b/migrations/2024-03-07-102620_add-network-transaction-id/down.sql
@@ -0,0 +1,3 @@
+-- This file should undo anything in `up.sql`
+
+ALTER TABLE payment_methods DROP COLUMN network_transaction_id;
\ No newline at end of file
diff --git a/migrations/2024-03-07-102620_add-network-transaction-id/up.sql b/migrations/2024-03-07-102620_add-network-transaction-id/up.sql
new file mode 100644
index 00000000000..06b199e6390
--- /dev/null
+++ b/migrations/2024-03-07-102620_add-network-transaction-id/up.sql
@@ -0,0 +1,3 @@
+-- Your SQL goes here
+
+ALTER TABLE payment_methods ADD COLUMN network_transaction_id VARCHAR(255) DEFAULT NULL;
\ No newline at end of file
|
2024-03-07T11:34:54Z
|
## 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 `network_transaction_id` column in the `payment_methods` table as it is required to store the NRID against the respective payment_method_id. This NRID will later be used processor agnostic MITs. This pr also adds application level config (`network_transactoin_id_supported_connectors`) that contains the list of connectors that support the `network_transaction_id`.
### 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)?
-->
columns in the `payment_methods` table

## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
aecf4aeacce33c3dc03e089ef6d62af93e29ca9a
|
|
juspay/hyperswitch
|
juspay__hyperswitch-4009
|
Bug: [BUG] Fix failing postman collections
### Feature Description
Fix failing postman collections for cybersource, checkout and bluesnap
### Possible Implementation
Add customer_acceptance for all the save card flows
### 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/postman/collection-dir/bankofamerica/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Confirm/request.json b/postman/collection-dir/bankofamerica/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Confirm/request.json
index 16f6e13983f..3ba8c394b4c 100644
--- a/postman/collection-dir/bankofamerica/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Confirm/request.json
+++ b/postman/collection-dir/bankofamerica/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Confirm/request.json
@@ -38,19 +38,21 @@
}
},
"raw_json_formatted": {
- "client_secret": "{{client_secret}}"
+ "client_secret": "{{client_secret}}",
+ "customer_acceptance": {
+ "acceptance_type": "online",
+ "accepted_at": "2022-09-10T10:11:12Z",
+ "online": {
+ "ip_address": "123.32.25.123",
+ "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36"
+ }
+ }
}
},
"url": {
"raw": "{{baseUrl}}/payments/:id/confirm",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments",
- ":id",
- "confirm"
- ],
+ "host": ["{{baseUrl}}"],
+ "path": ["payments", ":id", "confirm"],
"variable": [
{
"key": "id",
diff --git a/postman/collection-dir/bankofamerica/Flow Testcases/Happy Cases/Scenario4-Create payment with Manual capture/Payments - Create/request.json b/postman/collection-dir/bankofamerica/Flow Testcases/Happy Cases/Scenario4-Create payment with Manual capture/Payments - Create/request.json
index 878ea581a93..8bd119ed2fe 100644
--- a/postman/collection-dir/bankofamerica/Flow Testcases/Happy Cases/Scenario4-Create payment with Manual capture/Payments - Create/request.json
+++ b/postman/collection-dir/bankofamerica/Flow Testcases/Happy Cases/Scenario4-Create payment with Manual capture/Payments - Create/request.json
@@ -35,6 +35,14 @@
"authentication_type": "no_three_ds",
"return_url": "https://duck.com",
"setup_future_usage": "on_session",
+ "customer_acceptance": {
+ "acceptance_type": "online",
+ "accepted_at": "2022-09-10T10:11:12Z",
+ "online": {
+ "ip_address": "123.32.25.123",
+ "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36"
+ }
+ },
"payment_method": "card",
"payment_method_type": "debit",
"payment_method_data": {
@@ -87,12 +95,8 @@
},
"url": {
"raw": "{{baseUrl}}/payments",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments"
- ]
+ "host": ["{{baseUrl}}"],
+ "path": ["payments"]
},
"description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
}
diff --git a/postman/collection-dir/bankofamerica/Flow Testcases/Happy Cases/Scenario5-Void the payment/Payments - Create/request.json b/postman/collection-dir/bankofamerica/Flow Testcases/Happy Cases/Scenario5-Void the payment/Payments - Create/request.json
index 5e3ff0e70ad..8ea0f5f2039 100644
--- a/postman/collection-dir/bankofamerica/Flow Testcases/Happy Cases/Scenario5-Void the payment/Payments - Create/request.json
+++ b/postman/collection-dir/bankofamerica/Flow Testcases/Happy Cases/Scenario5-Void the payment/Payments - Create/request.json
@@ -35,6 +35,14 @@
"authentication_type": "no_three_ds",
"return_url": "https://duck.com",
"setup_future_usage": "on_session",
+ "customer_acceptance": {
+ "acceptance_type": "online",
+ "accepted_at": "2022-09-10T10:11:12Z",
+ "online": {
+ "ip_address": "123.32.25.123",
+ "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36"
+ }
+ },
"payment_method": "card",
"payment_method_type": "debit",
"payment_method_data": {
@@ -87,12 +95,8 @@
},
"url": {
"raw": "{{baseUrl}}/payments",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments"
- ]
+ "host": ["{{baseUrl}}"],
+ "path": ["payments"]
},
"description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
}
diff --git a/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario10-Save card flow/Payments - Create/request.json b/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario10-Save card flow/Payments - Create/request.json
index 6694ff2b22a..aa9635024c5 100644
--- a/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario10-Save card flow/Payments - Create/request.json
+++ b/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario10-Save card flow/Payments - Create/request.json
@@ -33,6 +33,14 @@
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"setup_future_usage": "on_session",
+ "customer_acceptance": {
+ "acceptance_type": "online",
+ "accepted_at": "2022-09-10T10:11:12Z",
+ "online": {
+ "ip_address": "123.32.25.123",
+ "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36"
+ }
+ },
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
@@ -89,12 +97,8 @@
},
"url": {
"raw": "{{baseUrl}}/payments",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments"
- ]
+ "host": ["{{baseUrl}}"],
+ "path": ["payments"]
},
"description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
}
diff --git a/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario11-Pass Invalid CVV for save card flow and verify failed payment Copy/Payments - Create/request.json b/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario11-Pass Invalid CVV for save card flow and verify failed payment Copy/Payments - Create/request.json
index 9260edb1a99..2b6e0287d48 100644
--- a/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario11-Pass Invalid CVV for save card flow and verify failed payment Copy/Payments - Create/request.json
+++ b/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario11-Pass Invalid CVV for save card flow and verify failed payment Copy/Payments - Create/request.json
@@ -33,6 +33,14 @@
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"setup_future_usage": "on_session",
+ "customer_acceptance": {
+ "acceptance_type": "online",
+ "accepted_at": "2022-09-10T10:11:12Z",
+ "online": {
+ "ip_address": "123.32.25.123",
+ "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36"
+ }
+ },
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
@@ -89,12 +97,8 @@
},
"url": {
"raw": "{{baseUrl}}/payments",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments"
- ]
+ "host": ["{{baseUrl}}"],
+ "path": ["payments"]
},
"description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
}
diff --git a/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture Copy/Payments - Create/request.json b/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture Copy/Payments - Create/request.json
index 9260edb1a99..2b6e0287d48 100644
--- a/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture Copy/Payments - Create/request.json
+++ b/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario12-Save card payment with manual capture Copy/Payments - Create/request.json
@@ -33,6 +33,14 @@
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"setup_future_usage": "on_session",
+ "customer_acceptance": {
+ "acceptance_type": "online",
+ "accepted_at": "2022-09-10T10:11:12Z",
+ "online": {
+ "ip_address": "123.32.25.123",
+ "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36"
+ }
+ },
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
@@ -89,12 +97,8 @@
},
"url": {
"raw": "{{baseUrl}}/payments",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments"
- ]
+ "host": ["{{baseUrl}}"],
+ "path": ["payments"]
},
"description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
}
diff --git a/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment Copy/Payments - Create/request.json b/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment Copy/Payments - Create/request.json
index 9260edb1a99..2b6e0287d48 100644
--- a/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment Copy/Payments - Create/request.json
+++ b/postman/collection-dir/bluesnap/Flow Testcases/Happy Cases/Scenario13-Don't Pass CVV for save card flow and verify success payment Copy/Payments - Create/request.json
@@ -33,6 +33,14 @@
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"setup_future_usage": "on_session",
+ "customer_acceptance": {
+ "acceptance_type": "online",
+ "accepted_at": "2022-09-10T10:11:12Z",
+ "online": {
+ "ip_address": "123.32.25.123",
+ "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36"
+ }
+ },
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
@@ -89,12 +97,8 @@
},
"url": {
"raw": "{{baseUrl}}/payments",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments"
- ]
+ "host": ["{{baseUrl}}"],
+ "path": ["payments"]
},
"description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
}
diff --git a/postman/collection-dir/checkout/Flow Testcases/Happy Cases/Scenario11-Save card flow/Payments - Create/request.json b/postman/collection-dir/checkout/Flow Testcases/Happy Cases/Scenario11-Save card flow/Payments - Create/request.json
index 9260edb1a99..2b6e0287d48 100644
--- a/postman/collection-dir/checkout/Flow Testcases/Happy Cases/Scenario11-Save card flow/Payments - Create/request.json
+++ b/postman/collection-dir/checkout/Flow Testcases/Happy Cases/Scenario11-Save card flow/Payments - Create/request.json
@@ -33,6 +33,14 @@
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"setup_future_usage": "on_session",
+ "customer_acceptance": {
+ "acceptance_type": "online",
+ "accepted_at": "2022-09-10T10:11:12Z",
+ "online": {
+ "ip_address": "123.32.25.123",
+ "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36"
+ }
+ },
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
@@ -89,12 +97,8 @@
},
"url": {
"raw": "{{baseUrl}}/payments",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments"
- ]
+ "host": ["{{baseUrl}}"],
+ "path": ["payments"]
},
"description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
}
diff --git a/postman/collection-dir/checkout/Flow Testcases/Happy Cases/Scenario12-Don't Pass CVV for save card flow and verify success payment/Payments - Create/request.json b/postman/collection-dir/checkout/Flow Testcases/Happy Cases/Scenario12-Don't Pass CVV for save card flow and verify success payment/Payments - Create/request.json
index 9260edb1a99..2b6e0287d48 100644
--- a/postman/collection-dir/checkout/Flow Testcases/Happy Cases/Scenario12-Don't Pass CVV for save card flow and verify success payment/Payments - Create/request.json
+++ b/postman/collection-dir/checkout/Flow Testcases/Happy Cases/Scenario12-Don't Pass CVV for save card flow and verify success payment/Payments - Create/request.json
@@ -33,6 +33,14 @@
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"setup_future_usage": "on_session",
+ "customer_acceptance": {
+ "acceptance_type": "online",
+ "accepted_at": "2022-09-10T10:11:12Z",
+ "online": {
+ "ip_address": "123.32.25.123",
+ "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36"
+ }
+ },
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
@@ -89,12 +97,8 @@
},
"url": {
"raw": "{{baseUrl}}/payments",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments"
- ]
+ "host": ["{{baseUrl}}"],
+ "path": ["payments"]
},
"description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
}
diff --git a/postman/collection-dir/checkout/Flow Testcases/Happy Cases/Scenario13-Pass Invalid CVV for save card flow and verify failed payment/Payments - Create/request.json b/postman/collection-dir/checkout/Flow Testcases/Happy Cases/Scenario13-Pass Invalid CVV for save card flow and verify failed payment/Payments - Create/request.json
index 9260edb1a99..2b6e0287d48 100644
--- a/postman/collection-dir/checkout/Flow Testcases/Happy Cases/Scenario13-Pass Invalid CVV for save card flow and verify failed payment/Payments - Create/request.json
+++ b/postman/collection-dir/checkout/Flow Testcases/Happy Cases/Scenario13-Pass Invalid CVV for save card flow and verify failed payment/Payments - Create/request.json
@@ -33,6 +33,14 @@
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"setup_future_usage": "on_session",
+ "customer_acceptance": {
+ "acceptance_type": "online",
+ "accepted_at": "2022-09-10T10:11:12Z",
+ "online": {
+ "ip_address": "123.32.25.123",
+ "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36"
+ }
+ },
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
@@ -89,12 +97,8 @@
},
"url": {
"raw": "{{baseUrl}}/payments",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments"
- ]
+ "host": ["{{baseUrl}}"],
+ "path": ["payments"]
},
"description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
}
diff --git a/postman/collection-dir/checkout/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Create/request.json b/postman/collection-dir/checkout/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Create/request.json
index 9260edb1a99..2b6e0287d48 100644
--- a/postman/collection-dir/checkout/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Create/request.json
+++ b/postman/collection-dir/checkout/Flow Testcases/Happy Cases/Scenario14-Save card payment with manual capture/Payments - Create/request.json
@@ -33,6 +33,14 @@
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"setup_future_usage": "on_session",
+ "customer_acceptance": {
+ "acceptance_type": "online",
+ "accepted_at": "2022-09-10T10:11:12Z",
+ "online": {
+ "ip_address": "123.32.25.123",
+ "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36"
+ }
+ },
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
@@ -89,12 +97,8 @@
},
"url": {
"raw": "{{baseUrl}}/payments",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments"
- ]
+ "host": ["{{baseUrl}}"],
+ "path": ["payments"]
},
"description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
}
diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario10-Don't Pass CVV for save card flow and verifysuccess payment/Payments - Create/request.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario10-Don't Pass CVV for save card flow and verifysuccess payment/Payments - Create/request.json
index d69394e2926..188c0b38676 100644
--- a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario10-Don't Pass CVV for save card flow and verifysuccess payment/Payments - Create/request.json
+++ b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario10-Don't Pass CVV for save card flow and verifysuccess payment/Payments - Create/request.json
@@ -33,6 +33,14 @@
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"setup_future_usage": "on_session",
+ "customer_acceptance": {
+ "acceptance_type": "online",
+ "accepted_at": "2022-09-10T10:11:12Z",
+ "online": {
+ "ip_address": "123.32.25.123",
+ "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36"
+ }
+ },
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
@@ -88,12 +96,8 @@
},
"url": {
"raw": "{{baseUrl}}/payments",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments"
- ]
+ "host": ["{{baseUrl}}"],
+ "path": ["payments"]
},
"description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
}
diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario11-Save card payment with manual capture/Payments - Create/request.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario11-Save card payment with manual capture/Payments - Create/request.json
index 5332a1326c1..f40ab119265 100644
--- a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario11-Save card payment with manual capture/Payments - Create/request.json
+++ b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario11-Save card payment with manual capture/Payments - Create/request.json
@@ -33,6 +33,14 @@
"authentication_type": "no_three_ds",
"return_url": "https://google.com",
"setup_future_usage": "on_session",
+ "customer_acceptance": {
+ "acceptance_type": "online",
+ "accepted_at": "2022-09-10T10:11:12Z",
+ "online": {
+ "ip_address": "123.32.25.123",
+ "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36"
+ }
+ },
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
@@ -88,12 +96,8 @@
},
"url": {
"raw": "{{baseUrl}}/payments",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments"
- ]
+ "host": ["{{baseUrl}}"],
+ "path": ["payments"]
},
"description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
}
diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario12-Zero auth mandates/Payments - Confirm/request.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario12-Zero auth mandates/Payments - Confirm/request.json
index ad06c8ad4bd..dbc19ce0181 100644
--- a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario12-Zero auth mandates/Payments - Confirm/request.json
+++ b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario12-Zero auth mandates/Payments - Confirm/request.json
@@ -82,14 +82,8 @@
},
"url": {
"raw": "{{baseUrl}}/payments/:id/confirm",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments",
- ":id",
- "confirm"
- ],
+ "host": ["{{baseUrl}}"],
+ "path": ["payments", ":id", "confirm"],
"variable": [
{
"key": "id",
diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario19-Create 3ds payment/Payments - Create/request.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario19-Create 3ds payment/Payments - Create/request.json
index e7fc25844ab..48692ab2b3e 100644
--- a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario19-Create 3ds payment/Payments - Create/request.json
+++ b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario19-Create 3ds payment/Payments - Create/request.json
@@ -29,6 +29,14 @@
"customer_id": "{{customer_id}}",
"email": "guest@example.com",
"setup_future_usage": "on_session",
+ "customer_acceptance": {
+ "acceptance_type": "online",
+ "accepted_at": "2022-09-10T10:11:12Z",
+ "online": {
+ "ip_address": "123.32.25.123",
+ "user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36"
+ }
+ },
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+65",
@@ -82,12 +90,8 @@
},
"url": {
"raw": "{{baseUrl}}/payments",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments"
- ]
+ "host": ["{{baseUrl}}"],
+ "path": ["payments"]
},
"description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
}
diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario20-Create 3ds mandate/Payments - Create/request.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario20-Create 3ds mandate/Payments - Create/request.json
index 0fc9b71ff57..261af340978 100644
--- a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario20-Create 3ds mandate/Payments - Create/request.json
+++ b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario20-Create 3ds mandate/Payments - Create/request.json
@@ -59,6 +59,14 @@
}
}
},
+ "customer_acceptance": {
+ "acceptance_type": "offline",
+ "accepted_at": "1963-05-03T04:07:52.723Z",
+ "online": {
+ "ip_address": "127.0.0.1",
+ "user_agent": "amet irure esse"
+ }
+ },
"shipping": {
"address": {
"line1": "1467",
@@ -95,12 +103,8 @@
},
"url": {
"raw": "{{baseUrl}}/payments",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments"
- ]
+ "host": ["{{baseUrl}}"],
+ "path": ["payments"]
},
"description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
}
diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario21-Create a mandate without customer acceptance/Payments - Confirm/request.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario21-Create a mandate without customer acceptance/Payments - Confirm/request.json
index c564a62c80e..6e5824386eb 100644
--- a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario21-Create a mandate without customer acceptance/Payments - Confirm/request.json
+++ b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario21-Create a mandate without customer acceptance/Payments - Confirm/request.json
@@ -66,6 +66,14 @@
}
}
},
+ "customer_acceptance": {
+ "acceptance_type": "offline",
+ "accepted_at": "1963-05-03T04:07:52.723Z",
+ "online": {
+ "ip_address": "127.0.0.1",
+ "user_agent": "amet irure esse"
+ }
+ },
"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",
@@ -82,14 +90,8 @@
},
"url": {
"raw": "{{baseUrl}}/payments/:id/confirm",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments",
- ":id",
- "confirm"
- ],
+ "host": ["{{baseUrl}}"],
+ "path": ["payments", ":id", "confirm"],
"variable": [
{
"key": "id",
diff --git a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario9-Add card flow/Payments - Confirm/request.json b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario9-Add card flow/Payments - Confirm/request.json
index fd771e557f8..9fd1a203309 100644
--- a/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario9-Add card flow/Payments - Confirm/request.json
+++ b/postman/collection-dir/cybersource/Flow Testcases/Happy Cases/Scenario9-Add card flow/Payments - Confirm/request.json
@@ -51,6 +51,14 @@
}
},
"setup_future_usage": "on_session",
+ "customer_acceptance": {
+ "acceptance_type": "offline",
+ "accepted_at": "1963-05-03T04:07:52.723Z",
+ "online": {
+ "ip_address": "127.0.0.1",
+ "user_agent": "amet irure esse"
+ }
+ },
"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",
@@ -67,14 +75,8 @@
},
"url": {
"raw": "{{baseUrl}}/payments/:id/confirm",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments",
- ":id",
- "confirm"
- ],
+ "host": ["{{baseUrl}}"],
+ "path": ["payments", ":id", "confirm"],
"variable": [
{
"key": "id",
diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Failure card/Payments - Create/request.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Failure card/Payments - Create/request.json
index 063c7b86048..93441083df2 100644
--- a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Failure card/Payments - Create/request.json
+++ b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario11-Failure card/Payments - Create/request.json
@@ -29,6 +29,14 @@
"customer_id": "{{customer_id}}",
"email": "guest@example.com",
"setup_future_usage": "on_session",
+ "customer_acceptance": {
+ "acceptance_type": "offline",
+ "accepted_at": "1963-05-03T04:07:52.723Z",
+ "online": {
+ "ip_address": "127.0.0.1",
+ "user_agent": "amet irure esse"
+ }
+ },
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+65",
@@ -82,12 +90,8 @@
},
"url": {
"raw": "{{baseUrl}}/payments",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments"
- ]
+ "host": ["{{baseUrl}}"],
+ "path": ["payments"]
},
"description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
}
diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario14-Recurring payment for revoked mandates/Payments - Create/request.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario14-Recurring payment for revoked mandates/Payments - Create/request.json
index f0be44bec91..5815567de25 100644
--- a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario14-Recurring payment for revoked mandates/Payments - Create/request.json
+++ b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario14-Recurring payment for revoked mandates/Payments - Create/request.json
@@ -59,6 +59,14 @@
}
}
},
+ "customer_acceptance": {
+ "acceptance_type": "offline",
+ "accepted_at": "1963-05-03T04:07:52.723Z",
+ "online": {
+ "ip_address": "127.0.0.1",
+ "user_agent": "amet irure esse"
+ }
+ },
"shipping": {
"address": {
"line1": "1467",
@@ -95,12 +103,8 @@
},
"url": {
"raw": "{{baseUrl}}/payments",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments"
- ]
+ "host": ["{{baseUrl}}"],
+ "path": ["payments"]
},
"description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
}
diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario15-Setup_future_usage is off_session for normal payments/Payments - Create/request.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario15-Setup_future_usage is off_session for normal payments/Payments - Create/request.json
index 5f55f09c9b4..7cb43e8b741 100644
--- a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario15-Setup_future_usage is off_session for normal payments/Payments - Create/request.json
+++ b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario15-Setup_future_usage is off_session for normal payments/Payments - Create/request.json
@@ -32,6 +32,14 @@
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"setup_future_usage": "off_session",
+ "customer_acceptance": {
+ "acceptance_type": "offline",
+ "accepted_at": "1963-05-03T04:07:52.723Z",
+ "online": {
+ "ip_address": "127.0.0.1",
+ "user_agent": "amet irure esse"
+ }
+ },
"return_url": "https://duck.com",
"billing": {
"address": {
@@ -69,12 +77,8 @@
},
"url": {
"raw": "{{baseUrl}}/payments",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments"
- ]
+ "host": ["{{baseUrl}}"],
+ "path": ["payments"]
},
"description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
}
diff --git a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json
index 4bf62f4f29f..fd997c7b6ba 100644
--- a/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json
+++ b/postman/collection-dir/cybersource/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json
@@ -59,6 +59,14 @@
}
}
},
+ "customer_acceptance": {
+ "acceptance_type": "offline",
+ "accepted_at": "1963-05-03T04:07:52.723Z",
+ "online": {
+ "ip_address": "127.0.0.1",
+ "user_agent": "amet irure esse"
+ }
+ },
"billing": {
"address": {
"line1": "1467",
@@ -95,12 +103,8 @@
},
"url": {
"raw": "{{baseUrl}}/payments",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments"
- ]
+ "host": ["{{baseUrl}}"],
+ "path": ["payments"]
},
"description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
}
diff --git a/postman/collection-dir/forte/Flow Testcases/Happy Cases/Scenario6-Create a mandate and recurring payment/Payments - Create/request.json b/postman/collection-dir/forte/Flow Testcases/Happy Cases/Scenario6-Create a mandate and recurring payment/Payments - Create/request.json
index a735ee48661..f9d3875c121 100644
--- a/postman/collection-dir/forte/Flow Testcases/Happy Cases/Scenario6-Create a mandate and recurring payment/Payments - Create/request.json
+++ b/postman/collection-dir/forte/Flow Testcases/Happy Cases/Scenario6-Create a mandate and recurring payment/Payments - Create/request.json
@@ -59,6 +59,14 @@
}
}
},
+ "customer_acceptance": {
+ "acceptance_type": "offline",
+ "accepted_at": "1963-05-03T04:07:52.723Z",
+ "online": {
+ "ip_address": "127.0.0.1",
+ "user_agent": "amet irure esse"
+ }
+ },
"billing": {
"address": {
"line1": "1467",
diff --git a/postman/collection-dir/forte/Flow Testcases/Variation Cases/Scenario6-Create a recurring payment with greater mandate amount/Payments - Create/request.json b/postman/collection-dir/forte/Flow Testcases/Variation Cases/Scenario6-Create a recurring payment with greater mandate amount/Payments - Create/request.json
index 52be363a049..36b559bcf62 100644
--- a/postman/collection-dir/forte/Flow Testcases/Variation Cases/Scenario6-Create a recurring payment with greater mandate amount/Payments - Create/request.json
+++ b/postman/collection-dir/forte/Flow Testcases/Variation Cases/Scenario6-Create a recurring payment with greater mandate amount/Payments - Create/request.json
@@ -59,6 +59,14 @@
}
}
},
+ "customer_acceptance": {
+ "acceptance_type": "offline",
+ "accepted_at": "1963-05-03T04:07:52.723Z",
+ "online": {
+ "ip_address": "127.0.0.1",
+ "user_agent": "amet irure esse"
+ }
+ },
"billing": {
"address": {
"line1": "1467",
diff --git a/postman/collection-dir/globalpay/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json b/postman/collection-dir/globalpay/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json
index 57d625e7c39..600979ea851 100644
--- a/postman/collection-dir/globalpay/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json
+++ b/postman/collection-dir/globalpay/Flow Testcases/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json
@@ -59,6 +59,14 @@
}
}
},
+ "customer_acceptance": {
+ "acceptance_type": "offline",
+ "accepted_at": "1963-05-03T04:07:52.723Z",
+ "online": {
+ "ip_address": "127.0.0.1",
+ "user_agent": "amet irure esse"
+ }
+ },
"billing": {
"address": {
"line1": "1467",
diff --git a/postman/collection-dir/hyperswitch/Hackathon/Happy Cases/Scenario11-Create a mandate and recurring payment/Payments - Create/request.json b/postman/collection-dir/hyperswitch/Hackathon/Happy Cases/Scenario11-Create a mandate and recurring payment/Payments - Create/request.json
index ed87e6ed332..b32011d26dc 100644
--- a/postman/collection-dir/hyperswitch/Hackathon/Happy Cases/Scenario11-Create a mandate and recurring payment/Payments - Create/request.json
+++ b/postman/collection-dir/hyperswitch/Hackathon/Happy Cases/Scenario11-Create a mandate and recurring payment/Payments - Create/request.json
@@ -59,6 +59,14 @@
}
}
},
+ "customer_acceptance": {
+ "acceptance_type": "offline",
+ "accepted_at": "1963-05-03T04:07:52.723Z",
+ "online": {
+ "ip_address": "127.0.0.1",
+ "user_agent": "amet irure esse"
+ }
+ },
"billing": {
"address": {
"line1": "1467",
diff --git a/postman/collection-dir/hyperswitch/Hackathon/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/request.json b/postman/collection-dir/hyperswitch/Hackathon/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/request.json
index d5cb30f4c1b..3db3bf69950 100644
--- a/postman/collection-dir/hyperswitch/Hackathon/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/request.json
+++ b/postman/collection-dir/hyperswitch/Hackathon/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/request.json
@@ -59,6 +59,14 @@
}
}
},
+ "customer_acceptance": {
+ "acceptance_type": "offline",
+ "accepted_at": "1963-05-03T04:07:52.723Z",
+ "online": {
+ "ip_address": "127.0.0.1",
+ "user_agent": "amet irure esse"
+ }
+ },
"shipping": {
"address": {
"line1": "1467",
diff --git a/postman/collection-dir/hyperswitch/Hackathon/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json b/postman/collection-dir/hyperswitch/Hackathon/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json
index ed87e6ed332..b32011d26dc 100644
--- a/postman/collection-dir/hyperswitch/Hackathon/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json
+++ b/postman/collection-dir/hyperswitch/Hackathon/Variation Cases/Scenario9-Create a recurring payment with greater mandate amount/Payments - Create/request.json
@@ -59,6 +59,14 @@
}
}
},
+ "customer_acceptance": {
+ "acceptance_type": "offline",
+ "accepted_at": "1963-05-03T04:07:52.723Z",
+ "online": {
+ "ip_address": "127.0.0.1",
+ "user_agent": "amet irure esse"
+ }
+ },
"billing": {
"address": {
"line1": "1467",
diff --git a/postman/collection-dir/hyperswitch/PaymentMethods/Payments - Create/request.json b/postman/collection-dir/hyperswitch/PaymentMethods/Payments - Create/request.json
index 20007308fe7..c7c7d114f5f 100644
--- a/postman/collection-dir/hyperswitch/PaymentMethods/Payments - Create/request.json
+++ b/postman/collection-dir/hyperswitch/PaymentMethods/Payments - Create/request.json
@@ -33,6 +33,14 @@
"authentication_type": "no_three_ds",
"return_url": "https://duck.com",
"setup_future_usage": "on_session",
+ "customer_acceptance": {
+ "acceptance_type": "offline",
+ "accepted_at": "1963-05-03T04:07:52.723Z",
+ "online": {
+ "ip_address": "127.0.0.1",
+ "user_agent": "amet irure esse"
+ }
+ },
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
diff --git a/postman/collection-dir/hyperswitch/Refunds/Payments - Create/request.json b/postman/collection-dir/hyperswitch/Refunds/Payments - Create/request.json
index 20007308fe7..c7c7d114f5f 100644
--- a/postman/collection-dir/hyperswitch/Refunds/Payments - Create/request.json
+++ b/postman/collection-dir/hyperswitch/Refunds/Payments - Create/request.json
@@ -33,6 +33,14 @@
"authentication_type": "no_three_ds",
"return_url": "https://duck.com",
"setup_future_usage": "on_session",
+ "customer_acceptance": {
+ "acceptance_type": "offline",
+ "accepted_at": "1963-05-03T04:07:52.723Z",
+ "online": {
+ "ip_address": "127.0.0.1",
+ "user_agent": "amet irure esse"
+ }
+ },
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
diff --git a/postman/collection-dir/multisafepay/Flow Testcases/Variation Cases/Scenario5-Create a recurring payment with greater mandate amount/Payments - Create/request.json b/postman/collection-dir/multisafepay/Flow Testcases/Variation Cases/Scenario5-Create a recurring payment with greater mandate amount/Payments - Create/request.json
index 011e150c4ec..10a0feda0a3 100644
--- a/postman/collection-dir/multisafepay/Flow Testcases/Variation Cases/Scenario5-Create a recurring payment with greater mandate amount/Payments - Create/request.json
+++ b/postman/collection-dir/multisafepay/Flow Testcases/Variation Cases/Scenario5-Create a recurring payment with greater mandate amount/Payments - Create/request.json
@@ -59,6 +59,14 @@
}
}
},
+ "customer_acceptance": {
+ "acceptance_type": "offline",
+ "accepted_at": "1963-05-03T04:07:52.723Z",
+ "online": {
+ "ip_address": "127.0.0.1",
+ "user_agent": "amet irure esse"
+ }
+ },
"billing": {
"address": {
"line1": "1467",
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Create/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Create/request.json
index 8e9afa774b3..c3143943700 100644
--- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Create/request.json
+++ b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario10-Create a mandate and recurring payment/Payments - Create/request.json
@@ -59,6 +59,14 @@
}
}
},
+ "customer_acceptance": {
+ "acceptance_type": "offline",
+ "accepted_at": "1963-05-03T04:07:52.723Z",
+ "online": {
+ "ip_address": "127.0.0.1",
+ "user_agent": "amet irure esse"
+ }
+ },
"billing": {
"address": {
"line1": "1467",
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/request.json
index 9c932aa537d..d7511caf779 100644
--- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/request.json
+++ b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario11-Refund recurring payment/Payments - Create/request.json
@@ -59,6 +59,14 @@
}
}
},
+ "customer_acceptance": {
+ "acceptance_type": "offline",
+ "accepted_at": "1963-05-03T04:07:52.723Z",
+ "online": {
+ "ip_address": "127.0.0.1",
+ "user_agent": "amet irure esse"
+ }
+ },
"shipping": {
"address": {
"line1": "1467",
diff --git a/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Lost Card)/request.json b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Lost Card)/request.json
index 9d317ce5293..5c8e5db8976 100644
--- a/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Lost Card)/request.json
+++ b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Create Payment with Invalid card/Payments - Create(Lost Card)/request.json
@@ -22,9 +22,7 @@
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
- "connector": [
- "nuvei"
- ],
+ "connector": ["nuvei"],
"customer_id": "futurebilling",
"email": "guest@example.com",
"name": "John Doe",
@@ -65,6 +63,14 @@
}
}
},
+ "customer_acceptance": {
+ "acceptance_type": "offline",
+ "accepted_at": "1963-05-03T04:07:52.723Z",
+ "online": {
+ "ip_address": "127.0.0.1",
+ "user_agent": "amet irure esse"
+ }
+ },
"billing": {
"address": {
"line1": "1467",
@@ -100,12 +106,8 @@
},
"url": {
"raw": "{{baseUrl}}/payments",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments"
- ]
+ "host": ["{{baseUrl}}"],
+ "path": ["payments"]
},
"description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
}
diff --git a/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Decline)/request.json b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Decline)/request.json
index 93f6d30da08..b3d0168f52d 100644
--- a/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Decline)/request.json
+++ b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Decline)/request.json
@@ -22,9 +22,7 @@
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
- "connector": [
- "nuvei"
- ],
+ "connector": ["nuvei"],
"customer_id": "futurebilling",
"email": "guest@example.com",
"name": "John Doe",
@@ -65,6 +63,14 @@
}
}
},
+ "customer_acceptance": {
+ "acceptance_type": "offline",
+ "accepted_at": "1963-05-03T04:07:52.723Z",
+ "online": {
+ "ip_address": "127.0.0.1",
+ "user_agent": "amet irure esse"
+ }
+ },
"billing": {
"address": {
"line1": "1467",
@@ -100,12 +106,8 @@
},
"url": {
"raw": "{{baseUrl}}/payments",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments"
- ]
+ "host": ["{{baseUrl}}"],
+ "path": ["payments"]
},
"description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
}
diff --git a/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Do Not Honor)/request.json b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Do Not Honor)/request.json
index b9cbf1fa7a5..b1cdc93dac8 100644
--- a/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Do Not Honor)/request.json
+++ b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Do Not Honor)/request.json
@@ -22,9 +22,7 @@
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
- "connector": [
- "nuvei"
- ],
+ "connector": ["nuvei"],
"customer_id": "futurebilling",
"email": "guest@example.com",
"name": "John Doe",
@@ -65,6 +63,14 @@
}
}
},
+ "customer_acceptance": {
+ "acceptance_type": "offline",
+ "accepted_at": "1963-05-03T04:07:52.723Z",
+ "online": {
+ "ip_address": "127.0.0.1",
+ "user_agent": "amet irure esse"
+ }
+ },
"billing": {
"address": {
"line1": "1467",
@@ -100,12 +106,8 @@
},
"url": {
"raw": "{{baseUrl}}/payments",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments"
- ]
+ "host": ["{{baseUrl}}"],
+ "path": ["payments"]
},
"description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
}
diff --git a/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Insufficient Funds)/request.json b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Insufficient Funds)/request.json
index 41edc08e2f9..10a6b680c8c 100644
--- a/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Insufficient Funds)/request.json
+++ b/postman/collection-dir/nuvei/Flow Testcases/Variation Cases/Scenario1- Payment Decline scenario/Payments - Create(Insufficient Funds)/request.json
@@ -22,9 +22,7 @@
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
- "connector": [
- "nuvei"
- ],
+ "connector": ["nuvei"],
"customer_id": "futurebilling",
"email": "guest@example.com",
"name": "John Doe",
@@ -65,6 +63,14 @@
}
}
},
+ "customer_acceptance": {
+ "acceptance_type": "offline",
+ "accepted_at": "1963-05-03T04:07:52.723Z",
+ "online": {
+ "ip_address": "127.0.0.1",
+ "user_agent": "amet irure esse"
+ }
+ },
"billing": {
"address": {
"line1": "1467",
@@ -100,12 +106,8 @@
},
"url": {
"raw": "{{baseUrl}}/payments",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments"
- ]
+ "host": ["{{baseUrl}}"],
+ "path": ["payments"]
},
"description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
}
|
2024-03-07T12:22:35Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
fix postman collections for saving cards with customer_acceptance
### 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?
<img width="1296" alt="Screenshot 2024-03-07 at 6 09 36 PM" src="https://github.com/juspay/hyperswitch/assets/55580080/a2d7f54b-e6b7-403e-982b-41a572ed70be">
## 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
|
f9b6f5da36c3a57da4b89db3151996403e2f3dfd
|
|
juspay/hyperswitch
|
juspay__hyperswitch-3995
|
Bug: [BUG] Outgoing webhook retry scheduler tasks remain in pending state if merchant webhook URL is not configured
### Bug Description
In the outgoing webhook retry process tracker (scheduler) workflow introduced in #3842, the process tracker entries added before the webhook is attempted to be delivered remain in the `process_started` status and `Pending` business status, if either:
1. The `webhook_details` field is not provided in the business profile (or merchant account with default profile).
2. The `webhook_details` is provided but the `webhook_url` within the `webhook_details` object is not provided.
3. The business profile initially had a webhoook URL configured but the profile was updated later to remove the webhook URL (or webhook details).
Since in any of the above cases the URL to deliver the webhook to the merchant is unavailable, the task can be aborted. Another optimization is to not create the outgoing webhook event (in the `events` database table) at all, if the merchant webhook URL is not available.
### Expected Behavior
- The event (and corresponding process tracker task) should not be created in the `events` table if the merchant webhook URL has not been configured.
- In case the business profile initially had a webhook URL configured and was later removed from the business profile, the retry tasks for previously failed webhooks should be aborted.
### Actual Behavior
The process tracker task remains in the `process_started` status and `Pending` business status.
### Steps To Reproduce
1. Create a merchant account without the `webhook_details` object or without the `webhook_url` field, using the API.
2. Create an API key, and create a merchant connector account.
3. Make a successful payment.
4. Query the `process_tracker` table in the database to search for workflows with the runner `OUTGOING_WEBHOOK_RETRY_WORKFLOW` and having the payment ID in the name:
```sql
SELECT * FROM process_tracker WHERE runner = 'OUTGOING_WEBHOOK_RETRY_WORKFLOW' AND id LIKE '%pay_1234%';
```
The `status` is `process_started` and the `business_status` of the task is `Pending`.
|
diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs
index 968181061a8..609337744d1 100644
--- a/crates/router/src/core/errors.rs
+++ b/crates/router/src/core/errors.rs
@@ -259,45 +259,44 @@ pub enum WebhooksFlowError {
#[error("Webhook details for merchant not configured")]
MerchantWebhookDetailsNotFound,
#[error("Merchant does not have a webhook URL configured")]
- MerchantWebhookURLNotConfigured,
- #[error("Payments core flow failed")]
- PaymentsCoreFailed,
- #[error("Refunds core flow failed")]
- RefundsCoreFailed,
- #[error("Dispuste core flow failed")]
- DisputeCoreFailed,
- #[error("Webhook event creation failed")]
- WebhookEventCreationFailed,
+ MerchantWebhookUrlNotConfigured,
#[error("Webhook event updation failed")]
WebhookEventUpdationFailed,
#[error("Outgoing webhook body signing failed")]
OutgoingWebhookSigningFailed,
- #[error("Unable to fork webhooks flow for outgoing webhooks")]
- ForkFlowFailed,
#[error("Webhook api call to merchant failed")]
CallToMerchantFailed,
#[error("Webhook not received by merchant")]
NotReceivedByMerchant,
- #[error("Resource not found")]
- ResourceNotFound,
- #[error("Webhook source verification failed")]
- WebhookSourceVerificationFailed,
- #[error("Webhook event object creation failed")]
- WebhookEventObjectCreationFailed,
- #[error("Not implemented")]
- NotImplemented,
#[error("Dispute webhook status validation failed")]
DisputeWebhookValidationFailed,
#[error("Outgoing webhook body encoding failed")]
OutgoingWebhookEncodingFailed,
- #[error("Missing required field: {field_name}")]
- MissingRequiredField { field_name: &'static str },
#[error("Failed to update outgoing webhook process tracker task")]
OutgoingWebhookProcessTrackerTaskUpdateFailed,
#[error("Failed to schedule retry attempt for outgoing webhook")]
OutgoingWebhookRetrySchedulingFailed,
}
+impl WebhooksFlowError {
+ pub(crate) fn is_webhook_delivery_retryable_error(&self) -> bool {
+ match self {
+ Self::MerchantConfigNotFound
+ | Self::MerchantWebhookDetailsNotFound
+ | Self::MerchantWebhookUrlNotConfigured => false,
+
+ Self::WebhookEventUpdationFailed
+ | Self::OutgoingWebhookSigningFailed
+ | Self::CallToMerchantFailed
+ | Self::NotReceivedByMerchant
+ | Self::DisputeWebhookValidationFailed
+ | Self::OutgoingWebhookEncodingFailed
+ | Self::OutgoingWebhookProcessTrackerTaskUpdateFailed
+ | Self::OutgoingWebhookRetrySchedulingFailed => true,
+ }
+ }
+}
+
#[derive(Debug, thiserror::Error)]
pub enum ApplePayDecryptionError {
#[error("Failed to base64 decode input data")]
diff --git a/crates/router/src/core/webhooks.rs b/crates/router/src/core/webhooks.rs
index b3e04e72f33..8d03bea06cb 100644
--- a/crates/router/src/core/webhooks.rs
+++ b/crates/router/src/core/webhooks.rs
@@ -659,8 +659,21 @@ pub(crate) async fn create_event_and_trigger_outgoing_webhook(
primary_object_type: enums::EventObjectType,
content: api::OutgoingWebhookContent,
) -> CustomResult<(), errors::ApiErrorResponse> {
- let merchant_id = business_profile.merchant_id.clone();
let event_id = format!("{primary_object_id}_{event_type}");
+
+ if !state.conf.webhooks.outgoing_enabled
+ || get_webhook_url_from_business_profile(&business_profile).is_err()
+ {
+ logger::debug!(
+ business_profile_id=%business_profile.profile_id,
+ %event_id,
+ "Outgoing webhooks are disabled in application configuration, or merchant webhook URL \
+ could not be obtained; skipping outgoing webhooks for event"
+ );
+ return Ok(());
+ }
+
+ let merchant_id = business_profile.merchant_id.clone();
let new_event = storage::EventNew {
event_id: event_id.clone(),
event_type,
@@ -688,50 +701,48 @@ pub(crate) async fn create_event_and_trigger_outgoing_webhook(
}
}?;
- if state.conf.webhooks.outgoing_enabled {
- let outgoing_webhook = api::OutgoingWebhook {
- merchant_id: merchant_id.clone(),
- event_id: event.event_id.clone(),
- event_type: event.event_type,
- content: content.clone(),
- timestamp: event.created_at,
- };
-
- let process_tracker = add_outgoing_webhook_retry_task_to_process_tracker(
- &*state.store,
- &business_profile,
- &event,
- )
- .await
- .map_err(|error| {
- logger::error!(
- ?error,
- "Failed to add outgoing webhook retry task to process tracker"
- );
- error
- })
- .ok();
+ let outgoing_webhook = api::OutgoingWebhook {
+ merchant_id: merchant_id.clone(),
+ event_id: event.event_id.clone(),
+ event_type: event.event_type,
+ content: content.clone(),
+ timestamp: event.created_at,
+ };
- // Using a tokio spawn here and not arbiter because not all caller of this function
- // may have an actix arbiter
- tokio::spawn(
- async move {
- trigger_appropriate_webhook_and_raise_event(
- state,
- merchant_account,
- business_profile,
- outgoing_webhook,
- types::WebhookDeliveryAttempt::InitialAttempt,
- content,
- event.event_id,
- event_type,
- process_tracker,
- )
- .await;
- }
- .in_current_span(),
+ let process_tracker = add_outgoing_webhook_retry_task_to_process_tracker(
+ &*state.store,
+ &business_profile,
+ &event,
+ )
+ .await
+ .map_err(|error| {
+ logger::error!(
+ ?error,
+ "Failed to add outgoing webhook retry task to process tracker"
);
- }
+ error
+ })
+ .ok();
+
+ // Using a tokio spawn here and not arbiter because not all caller of this function
+ // may have an actix arbiter
+ tokio::spawn(
+ async move {
+ trigger_appropriate_webhook_and_raise_event(
+ state,
+ merchant_account,
+ business_profile,
+ outgoing_webhook,
+ types::WebhookDeliveryAttempt::InitialAttempt,
+ content,
+ event.event_id,
+ event_type,
+ process_tracker,
+ )
+ .await;
+ }
+ .in_current_span(),
+ );
Ok(())
}
@@ -817,21 +828,30 @@ async fn trigger_webhook_to_merchant<W: types::OutgoingWebhookType>(
delivery_attempt: types::WebhookDeliveryAttempt,
process_tracker: Option<storage::ProcessTracker>,
) -> CustomResult<(), errors::WebhooksFlowError> {
- let webhook_details_json = business_profile
- .webhook_details
- .get_required_value("webhook_details")
- .change_context(errors::WebhooksFlowError::MerchantWebhookDetailsNotFound)?;
-
- let webhook_details: api::WebhookDetails =
- webhook_details_json
- .parse_value("WebhookDetails")
- .change_context(errors::WebhooksFlowError::MerchantWebhookDetailsNotFound)?;
-
- let webhook_url = webhook_details
- .webhook_url
- .get_required_value("webhook_url")
- .change_context(errors::WebhooksFlowError::MerchantWebhookURLNotConfigured)
- .map(ExposeInterface::expose)?;
+ let webhook_url = match (
+ get_webhook_url_from_business_profile(&business_profile),
+ process_tracker.clone(),
+ ) {
+ (Ok(webhook_url), _) => Ok(webhook_url),
+ (Err(error), Some(process_tracker)) => {
+ if !error
+ .current_context()
+ .is_webhook_delivery_retryable_error()
+ {
+ logger::debug!("Failed to obtain merchant webhook URL, aborting retries");
+ state
+ .store
+ .as_scheduler()
+ .finish_process_with_business_status(process_tracker, "FAILURE".into())
+ .await
+ .change_context(
+ errors::WebhooksFlowError::OutgoingWebhookProcessTrackerTaskUpdateFailed,
+ )?;
+ }
+ Err(error)
+ }
+ (Err(error), None) => Err(error),
+ }?;
let outgoing_webhook_event_id = webhook.event_id.clone();
@@ -1579,7 +1599,7 @@ pub async fn add_outgoing_webhook_retry_task_to_process_tracker(
let process_tracker_id = scheduler::utils::get_process_tracker_id(
runner,
task,
- &event.primary_object_id,
+ &event.event_id,
&business_profile.merchant_id,
);
let process_tracker_entry = storage::ProcessTrackerNew::new(
@@ -1611,3 +1631,24 @@ pub async fn add_outgoing_webhook_retry_task_to_process_tracker(
}
}
}
+
+fn get_webhook_url_from_business_profile(
+ business_profile: &diesel_models::business_profile::BusinessProfile,
+) -> CustomResult<String, errors::WebhooksFlowError> {
+ let webhook_details_json = business_profile
+ .webhook_details
+ .clone()
+ .get_required_value("webhook_details")
+ .change_context(errors::WebhooksFlowError::MerchantWebhookDetailsNotFound)?;
+
+ let webhook_details: api::WebhookDetails =
+ webhook_details_json
+ .parse_value("WebhookDetails")
+ .change_context(errors::WebhooksFlowError::MerchantWebhookDetailsNotFound)?;
+
+ webhook_details
+ .webhook_url
+ .get_required_value("webhook_url")
+ .change_context(errors::WebhooksFlowError::MerchantWebhookUrlNotConfigured)
+ .map(ExposeInterface::expose)
+}
|
2024-03-06T20:36:25Z
|
## 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 bug in the outgoing webhook retry workflow where process tracker tasks remained in pending state if merchant webhook URL was not configured in the business profile. For more information, see: #3995.
In addition, this PR includes these changes:
1. Updates the process tracker task ID format to include the event ID instead of the primary resource ID.
2. Removes unused enum variants from the `WebhooksFlowError` error enum.
The PR can easily be reviewed one commit at a time.
## 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).
-->
Fixes #3995.
## 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)?
-->
Locally, by running `router`, `producer` and `consumer`, and testing for these three cases:
1. For a business profile with webhook URL configured, the behavior should remain as before: webhooks should either be delivered successfully in the first attempt, or scheduled for later retries.
1. Screenshot of a webhook delivered in the initial attempt (business status is `INITIAL_DELIVERY_ATTEMPT_SUCCESSFUL`):

2. Screenshot of a webhook delivered during a retry attempt (business status is `COMPLETED_BY_PT` and retry count is positive):

2. For a business profile without `webhook_url` (or `webhook_details`) configured, the event is not created in the `events` table (and no process tracker task), and the `router` service displays a log line about the same:

The absence of the event in the `events` table and the process tracker task in the `process_tracker` table can be confirmed using the SQL queries, no rows should be returned in either case:
```sql
SELECT * FROM events WHERE event_id = 'event_id';
SELECT * FROM process_tracker WHERE runner = 'OUTGOING_WEBHOOK_RETRY_WORKFLOW' AND id LIKE '%event_id%';
```
3. For a business profile with a webhook URL configured initially but later updated to not include the `webhook_url` field or the `webhook_details` object, the task is aborted by the consumer:
1. The business status is `FAILURE`, and retry count is positive:

2. In addition, the `consumer` service displays a log line about the task being aborted.

The process tracker tasks in the above cases can be queried by using the SQL command, substituting the resource ID:
```sql
SELECT * FROM process_tracker WHERE runner = 'OUTGOING_WEBHOOK_RETRY_WORKFLOW' AND id LIKE '%pay_1234%';
```
## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
0aa40cbae75fd4cf5b13cfc518ff761b2b673246
|
|
juspay/hyperswitch
|
juspay__hyperswitch-3992
|
Bug: Create a merchant config for enable `pg_agnostic_mit`
Create a merchant config (`pg_agnostic_mit`) to enable usage of Network Transaction/Reference ID in recurring mandate payments. This will be a `business profile` level config that a merchant specifies.
**API Spec:-**
```
POST /business_profile/{bp_id}/configs/pg_agnostic_mit
{
“enabled”: true,
}
```
|
diff --git a/crates/api_models/src/routing.rs b/crates/api_models/src/routing.rs
index 4d32f1d0f81..723e6eccc36 100644
--- a/crates/api_models/src/routing.rs
+++ b/crates/api_models/src/routing.rs
@@ -11,7 +11,7 @@ pub use euclid::{
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
-use crate::enums::{self, RoutableConnectors, TransactionType};
+use crate::enums::{RoutableConnectors, TransactionType};
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
#[serde(tag = "type", content = "data", rename_all = "snake_case")]
@@ -299,35 +299,13 @@ impl From<RoutableConnectorChoice> for ast::ConnectorChoice {
}
}
-#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
pub struct DetailedConnectorChoice {
- pub connector: RoutableConnectors,
- pub business_label: Option<String>,
- pub business_country: Option<enums::CountryAlpha2>,
- pub business_sub_label: Option<String>,
-}
-
-impl DetailedConnectorChoice {
- pub fn get_connector_label(&self) -> Option<String> {
- self.business_country
- .as_ref()
- .zip(self.business_label.as_ref())
- .map(|(business_country, business_label)| {
- let mut base_label = format!(
- "{}_{:?}_{}",
- self.connector, business_country, business_label
- );
-
- if let Some(ref sub_label) = self.business_sub_label {
- base_label.push('_');
- base_label.push_str(sub_label);
- }
-
- base_label
- })
- }
+ pub enabled: bool,
}
+impl common_utils::events::ApiEventMetric for DetailedConnectorChoice {}
+
#[derive(Debug, Copy, Clone, serde::Serialize, serde::Deserialize, strum::Display, ToSchema)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rs
index 31825617398..bec90c51e9c 100644
--- a/crates/router/src/core/routing.rs
+++ b/crates/router/src/core/routing.rs
@@ -9,7 +9,6 @@ use api_models::{
};
#[cfg(not(feature = "business_profile_routing"))]
use common_utils::ext_traits::{Encode, StringExt};
-#[cfg(not(feature = "business_profile_routing"))]
use diesel_models::configs;
#[cfg(feature = "business_profile_routing")]
use diesel_models::routing_algorithm::RoutingAlgorithm;
@@ -807,6 +806,37 @@ pub async fn retrieve_linked_routing_config(
}
}
+pub async fn upsert_connector_agnostic_mandate_config(
+ state: AppState,
+ business_profile_id: &str,
+ mandate_config: routing_types::DetailedConnectorChoice,
+) -> RouterResponse<routing_types::DetailedConnectorChoice> {
+ let key = helpers::get_pg_agnostic_mandate_config_key(business_profile_id);
+
+ let mandate_config_str = mandate_config.enabled.to_string();
+
+ let find_config = state
+ .store
+ .find_config_by_key_unwrap_or(&key, Some(mandate_config_str.clone()))
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("error saving pg agnostic mandate config to db")?;
+
+ if find_config.config != mandate_config_str {
+ let config_update = configs::ConfigUpdate::Update {
+ config: Some(mandate_config_str),
+ };
+ state
+ .store
+ .update_config_by_key(&key, config_update)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("error saving pg agnostic mandate config to db")?;
+ }
+
+ Ok(service_api::ApplicationResponse::Json(mandate_config))
+}
+
pub async fn retrieve_default_routing_config_for_profiles(
state: AppState,
merchant_account: domain::MerchantAccount,
diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs
index febd1cd86dd..a725cc714e2 100644
--- a/crates/router/src/core/routing/helpers.rs
+++ b/crates/router/src/core/routing/helpers.rs
@@ -273,9 +273,9 @@ pub async fn update_business_profile_active_algorithm_ref(
pub async fn get_merchant_connector_agnostic_mandate_config(
db: &dyn StorageInterface,
- merchant_id: &str,
+ business_profile_id: &str,
) -> RouterResult<Vec<routing_types::DetailedConnectorChoice>> {
- let key = get_pg_agnostic_mandate_config_key(merchant_id);
+ let key = get_pg_agnostic_mandate_config_key(business_profile_id);
let maybe_config = db.find_config_by_key(&key).await;
match maybe_config {
@@ -312,29 +312,6 @@ pub async fn get_merchant_connector_agnostic_mandate_config(
}
}
-pub async fn update_merchant_connector_agnostic_mandate_config(
- db: &dyn StorageInterface,
- merchant_id: &str,
- mandate_config: Vec<routing_types::DetailedConnectorChoice>,
-) -> RouterResult<Vec<routing_types::DetailedConnectorChoice>> {
- let key = get_pg_agnostic_mandate_config_key(merchant_id);
- let mandate_config_str = mandate_config
- .encode_to_string_of_json()
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("unable to serialize pg agnostic mandate config during update")?;
-
- let config_update = configs::ConfigUpdate::Update {
- config: Some(mandate_config_str),
- };
-
- db.update_config_by_key(&key, config_update)
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("error saving pg agnostic mandate config to db")?;
-
- Ok(mandate_config)
-}
-
pub async fn validate_connectors_in_routing_config(
db: &dyn StorageInterface,
key_store: &domain::MerchantKeyStore,
@@ -465,8 +442,8 @@ pub fn get_routing_dictionary_key(merchant_id: &str) -> String {
/// Provides the identifier for the specific merchant's agnostic_mandate_config
#[inline(always)]
-pub fn get_pg_agnostic_mandate_config_key(merchant_id: &str) -> String {
- format!("pg_agnostic_mandate_{merchant_id}")
+pub fn get_pg_agnostic_mandate_config_key(business_profile_id: &str) -> String {
+ format!("pg_agnostic_mandate_{business_profile_id}")
}
/// Provides the identifier for the specific merchant's default_config
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 01ed994a9d3..7d9ee1670dc 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -437,6 +437,10 @@ impl Routing {
)
})),
)
+ .service(
+ web::resource("/business_profile/{business_profile_id}/configs/pg_agnostic_mit")
+ .route(web::post().to(cloud_routing::upsert_connector_agnostic_mandate_config)),
+ )
.service(
web::resource("/default")
.route(web::get().to(|state, req| {
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index 7908b9dfdca..02a3a6841f4 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -225,6 +225,7 @@ impl From<Flow> for ApiIdentifier {
| Flow::ReconTokenRequest
| Flow::ReconServiceRequest
| Flow::ReconVerifyToken => Self::Recon,
+ Flow::CreateConnectorAgnosticMandateConfig => Self::Routing,
}
}
}
diff --git a/crates/router/src/routes/routing.rs b/crates/router/src/routes/routing.rs
index 1476fc7b3d6..28d65f66a82 100644
--- a/crates/router/src/routes/routing.rs
+++ b/crates/router/src/routes/routing.rs
@@ -566,6 +566,44 @@ pub async fn routing_retrieve_linked_config(
}
}
+#[cfg(feature = "olap")]
+#[instrument(skip_all)]
+pub async fn upsert_connector_agnostic_mandate_config(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ json_payload: web::Json<routing_types::DetailedConnectorChoice>,
+ path: web::Path<String>,
+) -> impl Responder {
+ use crate::services::authentication::AuthenticationData;
+
+ let flow = Flow::CreateConnectorAgnosticMandateConfig;
+ let business_profile_id = path.into_inner();
+
+ Box::pin(oss_api::server_wrap(
+ flow,
+ state,
+ &req,
+ json_payload.into_inner(),
+ |state, _auth: AuthenticationData, mandate_config| {
+ Box::pin(routing::upsert_connector_agnostic_mandate_config(
+ state,
+ &business_profile_id,
+ mandate_config,
+ ))
+ },
+ #[cfg(not(feature = "release"))]
+ auth::auth_type(
+ &auth::ApiKeyAuth,
+ &auth::JWTAuth(Permission::RoutingWrite),
+ req.headers(),
+ ),
+ #[cfg(feature = "release")]
+ &auth::JWTAuth(Permission::RoutingWrite),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
#[cfg(feature = "olap")]
#[instrument(skip_all)]
pub async fn routing_retrieve_default_config_for_profiles(
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index df322da9429..ca8d75b3324 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -206,6 +206,8 @@ pub enum Flow {
RoutingRetrieveConfig,
/// Routing retrieve active config
RoutingRetrieveActiveConfig,
+ /// Update connector agnostic mandate config
+ CreateConnectorAgnosticMandateConfig,
/// Routing retrieve default config
RoutingRetrieveDefaultConfig,
/// Routing retrieve dictionary
|
2024-03-08T14:19:25Z
|
## 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 a merchant config (`pg_agnostic_mit`) to enable usage of Network Transaction/Reference ID in recurring `MIT` payments. This will be a `business profile` level config that a merchant specifies.
### 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)?
-->
Set processor agnostic MIT config as `true`
<img width="737" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/76c54b6a-888c-42fc-b5b2-024eecabf868">
config status from db

Set processor agnostic MIT config as `false`
<img width="654" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/e0dbd263-bc26-4167-ae96-f6a65cd0730c">
config status from db

```curl
curl --location 'https://sandbox.hyperswitch.io/routing/business_profile/:business_profile_id/configs/pg_agnostic_mit' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'Authorization: Bearer JWT_Token' \
--data '{
"enabled": true
}'
```
## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
aecf4aeacce33c3dc03e089ef6d62af93e29ca9a
|
|
juspay/hyperswitch
|
juspay__hyperswitch-3993
|
Bug: Route payments across `nrid_supported_connectors` if `pg_agnostic_mit`
For the MITs check for the `pg_agnostic_mit` config flag, if it is `enabled` then apply the routing rule for the list of pg_agnostic connectors. In this case we need to apply the same routing rules which is configured for the other payments by applying the pg_agnostic connector filter.
|
diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs
index 45aeb1e9074..19a37ab0fb7 100644
--- a/crates/router/src/connector/stripe/transformers.rs
+++ b/crates/router/src/connector/stripe/transformers.rs
@@ -136,6 +136,7 @@ pub struct PaymentIntentRequest {
#[serde(flatten)]
pub payment_data: Option<StripePaymentMethodData>,
pub capture_method: StripeCaptureMethod,
+ #[serde(flatten)]
pub payment_method_options: Option<StripePaymentMethodOptions>, // For mandate txns using network_txns_id, needs to be validated
pub setup_future_usage: Option<enums::FutureUsage>,
pub off_session: Option<bool>,
@@ -189,9 +190,9 @@ pub struct StripeCardData {
#[serde(rename = "payment_method_data[card][exp_year]")]
pub payment_method_data_card_exp_year: Secret<String>,
#[serde(rename = "payment_method_data[card][cvc]")]
- pub payment_method_data_card_cvc: Secret<String>,
+ pub payment_method_data_card_cvc: Option<Secret<String>>,
#[serde(rename = "payment_method_options[card][request_three_d_secure]")]
- pub payment_method_auth_type: Auth3ds,
+ pub payment_method_auth_type: Option<Auth3ds>,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct StripePayLaterData {
@@ -1498,8 +1499,8 @@ impl TryFrom<(&domain::Card, Auth3ds)> for StripePaymentMethodData {
payment_method_data_card_number: card.card_number.clone(),
payment_method_data_card_exp_month: card.card_exp_month.clone(),
payment_method_data_card_exp_year: card.card_exp_year.clone(),
- payment_method_data_card_cvc: card.card_cvc.clone(),
- payment_method_auth_type,
+ payment_method_data_card_cvc: Some(card.card_cvc.clone()),
+ payment_method_auth_type: Some(payment_method_auth_type),
}))
}
}
@@ -1821,7 +1822,44 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentIntentRequest {
network_transaction_id: Secret::new(network_transaction_id),
}),
});
- (None, None, StripeBillingAddress::default(), None)
+
+ let payment_data = match item.request.payment_method_data {
+ domain::payments::PaymentMethodData::Card(ref card) => {
+ StripePaymentMethodData::Card(StripeCardData {
+ payment_method_data_type: StripePaymentMethodType::Card,
+ payment_method_data_card_number: card.card_number.clone(),
+ payment_method_data_card_exp_month: card.card_exp_month.clone(),
+ payment_method_data_card_exp_year: card.card_exp_year.clone(),
+ payment_method_data_card_cvc: None,
+ payment_method_auth_type: None,
+ })
+ }
+ domain::payments::PaymentMethodData::CardRedirect(_)
+ | domain::payments::PaymentMethodData::Wallet(_)
+ | domain::payments::PaymentMethodData::PayLater(_)
+ | domain::payments::PaymentMethodData::BankRedirect(_)
+ | domain::payments::PaymentMethodData::BankDebit(_)
+ | domain::payments::PaymentMethodData::BankTransfer(_)
+ | domain::payments::PaymentMethodData::Crypto(_)
+ | domain::payments::PaymentMethodData::MandatePayment
+ | domain::payments::PaymentMethodData::Reward
+ | domain::payments::PaymentMethodData::Upi(_)
+ | domain::payments::PaymentMethodData::Voucher(_)
+ | domain::payments::PaymentMethodData::GiftCard(_)
+ | domain::payments::PaymentMethodData::CardToken(_) => {
+ Err(errors::ConnectorError::NotSupported {
+ message: "Network tokenization for payment method".to_string(),
+ connector: "Stripe",
+ })?
+ }
+ };
+
+ (
+ Some(payment_data),
+ None,
+ StripeBillingAddress::default(),
+ None,
+ )
}
_ => {
let (payment_method_data, payment_method_type, billing_address) =
@@ -3105,10 +3143,13 @@ impl TryFrom<&types::PaymentsCancelRouterData> for CancelRequest {
#[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)]
#[non_exhaustive]
#[serde(rename_all = "snake_case")]
+#[serde(untagged)]
pub enum StripePaymentMethodOptions {
Card {
mandate_options: Option<StripeMandateOptions>,
+ #[serde(rename = "payment_method_options[card][network_transaction_id]")]
network_transaction_id: Option<Secret<String>>,
+ #[serde(flatten)]
mit_exemption: Option<MitExemption>, // To be used for MIT mandate txns
},
Klarna {},
@@ -3139,6 +3180,7 @@ pub enum StripePaymentMethodOptions {
#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
pub struct MitExemption {
+ #[serde(rename = "payment_method_options[card][mit_exemption][network_transaction_id]")]
pub network_transaction_id: Secret<String>,
}
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index e7ec99f61b6..22f7cb311c6 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -2929,10 +2929,12 @@ where
.attach_printable("Invalid connector name received")?;
return decide_multiplex_connector_for_normal_or_recurring_payment(
+ &state,
payment_data,
routing_data,
connector_data,
- );
+ )
+ .await;
}
if let Some(ref routing_algorithm) = routing_data.routing_info.algorithm {
@@ -2983,10 +2985,12 @@ where
.attach_printable("Invalid connector name received")?;
return decide_multiplex_connector_for_normal_or_recurring_payment(
+ &state,
payment_data,
routing_data,
connector_data,
- );
+ )
+ .await;
}
route_connector_v1(
@@ -3001,7 +3005,8 @@ where
.await
}
-pub fn decide_multiplex_connector_for_normal_or_recurring_payment<F: Clone>(
+pub async fn decide_multiplex_connector_for_normal_or_recurring_payment<F: Clone>(
+ state: &AppState,
payment_data: &mut PaymentData<F>,
routing_data: &mut storage::RoutingData,
connectors: Vec<api::ConnectorData>,
@@ -3010,9 +3015,11 @@ pub fn decide_multiplex_connector_for_normal_or_recurring_payment<F: Clone>(
payment_data.payment_intent.setup_future_usage,
payment_data.token_data.as_ref(),
payment_data.recurring_details.as_ref(),
+ payment_data.payment_intent.off_session,
) {
- (Some(storage_enums::FutureUsage::OffSession), Some(_), None)
- | (None, None, Some(RecurringDetails::PaymentMethodId(_))) => {
+ (Some(storage_enums::FutureUsage::OffSession), Some(_), None, None)
+ | (None, None, Some(RecurringDetails::PaymentMethodId(_)), Some(true))
+ | (None, Some(_), None, Some(true)) => {
logger::debug!("performing routing for token-based MIT flow");
let payment_method_info = payment_data
@@ -3020,32 +3027,108 @@ pub fn decide_multiplex_connector_for_normal_or_recurring_payment<F: Clone>(
.as_ref()
.get_required_value("payment_method_info")?;
- let connector_mandate_details = payment_method_info
- .connector_mandate_details
- .clone()
- .map(|details| {
- details.parse_value::<storage::PaymentsMandateReference>("connector_mandate_details")
- })
- .transpose()
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("unable to deserialize connector mandate details")?
- .get_required_value("connector_mandate_details")
- .change_context(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)
- .attach_printable("no eligible connector found for token-based MIT flow since there were no connector mandate details")?;
+ let connector_mandate_details = &payment_method_info
+ .connector_mandate_details
+ .clone()
+ .map(|details| {
+ details.parse_value::<storage::PaymentsMandateReference>(
+ "connector_mandate_details",
+ )
+ })
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("unable to deserialize connector mandate details")?;
+
+ let profile_id = payment_data
+ .payment_intent
+ .profile_id
+ .as_ref()
+ .ok_or(errors::ApiErrorResponse::ResourceIdNotFound)?;
+
+ let pg_agnostic = state
+ .store
+ .find_config_by_key_unwrap_or(
+ &format!("pg_agnostic_mandate_{}", profile_id),
+ Some("false".to_string()),
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("The pg_agnostic config was not found in the DB")?;
let mut connector_choice = None;
+
for connector_data in connectors {
- if let Some(merchant_connector_id) = connector_data.merchant_connector_id.as_ref() {
- if let Some(mandate_reference_record) =
- connector_mandate_details.get(merchant_connector_id)
+ let merchant_connector_id = connector_data
+ .merchant_connector_id
+ .as_ref()
+ .ok_or(errors::ApiErrorResponse::InternalServerError)?;
+
+ if is_network_transaction_id_flow(
+ state,
+ &pg_agnostic.config,
+ connector_data.connector_name,
+ payment_method_info,
+ ) {
+ let network_transaction_id = payment_method_info
+ .network_transaction_id
+ .as_ref()
+ .ok_or(errors::ApiErrorResponse::InternalServerError)?;
+
+ let mandate_reference_id =
+ Some(payments_api::MandateReferenceId::NetworkMandateId(
+ network_transaction_id.to_string(),
+ ));
+
+ connector_choice = Some((connector_data, mandate_reference_id.clone()));
+ break;
+ } else if connector_mandate_details
+ .clone()
+ .map(|connector_mandate_details| {
+ connector_mandate_details.contains_key(merchant_connector_id)
+ })
+ .unwrap_or(false)
+ {
+ if let Some(merchant_connector_id) =
+ connector_data.merchant_connector_id.as_ref()
{
- connector_choice = Some((connector_data, mandate_reference_record.clone()));
- break;
+ if let Some(mandate_reference_record) = connector_mandate_details.clone()
+ .get_required_value("connector_mandate_details")
+ .change_context(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)
+ .attach_printable("no eligible connector found for token-based MIT flow since there were no connector mandate details")?
+ .get(merchant_connector_id)
+ {
+ let mandate_reference_id =
+ Some(payments_api::MandateReferenceId::ConnectorMandateId(
+ payments_api::ConnectorMandateReferenceId {
+ connector_mandate_id: Some(
+ mandate_reference_record.connector_mandate_id.clone(),
+ ),
+ payment_method_id: Some(
+ payment_method_info.payment_method_id.clone(),
+ ),
+ update_history: None,
+ },
+ ));
+ payment_data.recurring_mandate_payment_data =
+ Some(RecurringMandatePaymentData {
+ payment_method_type: mandate_reference_record
+ .payment_method_type,
+ original_payment_authorized_amount: mandate_reference_record
+ .original_payment_authorized_amount,
+ original_payment_authorized_currency: mandate_reference_record
+ .original_payment_authorized_currency,
+ });
+
+ connector_choice = Some((connector_data, mandate_reference_id.clone()));
+ break;
+ }
}
+ } else {
+ continue;
}
}
- let (chosen_connector_data, mandate_reference_record) = connector_choice
+ let (chosen_connector_data, mandate_reference_id) = connector_choice
.get_required_value("connector_choice")
.change_context(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)
.attach_printable("no eligible connector found for token-based MIT payment")?;
@@ -3056,26 +3139,16 @@ pub fn decide_multiplex_connector_for_normal_or_recurring_payment<F: Clone>(
routing_data.merchant_connector_id =
chosen_connector_data.merchant_connector_id.clone();
}
+ routing_data.routed_through = Some(chosen_connector_data.connector_name.to_string());
+ #[cfg(feature = "connector_choice_mca_id")]
+ {
+ routing_data.merchant_connector_id =
+ chosen_connector_data.merchant_connector_id.clone();
+ }
payment_data.mandate_id = Some(payments_api::MandateIds {
mandate_id: None,
- mandate_reference_id: Some(payments_api::MandateReferenceId::ConnectorMandateId(
- payments_api::ConnectorMandateReferenceId {
- connector_mandate_id: Some(
- mandate_reference_record.connector_mandate_id.clone(),
- ),
- payment_method_id: Some(payment_method_info.payment_method_id.clone()),
- update_history: None,
- },
- )),
- });
-
- payment_data.recurring_mandate_payment_data = Some(RecurringMandatePaymentData {
- payment_method_type: mandate_reference_record.payment_method_type,
- original_payment_authorized_amount: mandate_reference_record
- .original_payment_authorized_amount,
- original_payment_authorized_currency: mandate_reference_record
- .original_payment_authorized_currency,
+ mandate_reference_id,
});
Ok(api::ConnectorCallType::PreDetermined(chosen_connector_data))
@@ -3098,6 +3171,23 @@ pub fn decide_multiplex_connector_for_normal_or_recurring_payment<F: Clone>(
}
}
+pub fn is_network_transaction_id_flow(
+ state: &AppState,
+ pg_agnostic: &String,
+ connector: enums::Connector,
+ payment_method_info: &storage::PaymentMethod,
+) -> bool {
+ let ntid_supported_connectors = &state
+ .conf
+ .network_transaction_id_supported_connectors
+ .connector_list;
+
+ pg_agnostic == "true"
+ && payment_method_info.payment_method == storage_enums::PaymentMethod::Card
+ && ntid_supported_connectors.contains(&connector)
+ && payment_method_info.network_transaction_id.is_some()
+}
+
pub fn should_add_task_to_process_tracker<F: Clone>(payment_data: &PaymentData<F>) -> bool {
let connector = payment_data.payment_attempt.connector.as_deref();
@@ -3315,10 +3405,12 @@ where
match transaction_data {
TransactionData::Payment(payment_data) => {
decide_multiplex_connector_for_normal_or_recurring_payment(
+ state,
payment_data,
routing_data,
connector_data,
)
+ .await
}
#[cfg(feature = "payouts")]
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index 4eac9c1f4de..5214ce3f7a7 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -413,8 +413,11 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
payment_attempt.payment_method = payment_method.or(payment_attempt.payment_method);
payment_attempt.browser_info = browser_info;
- payment_attempt.payment_method_type =
- payment_method_type.or(payment_attempt.payment_method_type);
+ payment_attempt.payment_method_type = payment_method_type
+ .or(payment_attempt.payment_method_type)
+ .or(payment_method_info
+ .as_ref()
+ .and_then(|pm_info| pm_info.payment_method_type));
payment_attempt.payment_experience = request
.payment_experience
diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs
index f418b660380..70cf702311d 100644
--- a/crates/router/src/core/payments/operations/payment_response.rs
+++ b/crates/router/src/core/payments/operations/payment_response.rs
@@ -972,18 +972,46 @@ async fn update_payment_method_status_and_ntid<F: Clone>(
.find_payment_method(id)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
- let network_transaction_id = payment_response
- .map(|resp| match resp {
- crate::types::PaymentsResponseData::TransactionResponse { network_txn_id, .. } => {
- network_txn_id.to_owned()
+
+ let pm_resp_network_transaction_id = payment_response
+ .map(|resp| if let types::PaymentsResponseData::TransactionResponse { network_txn_id: network_transaction_id, .. } = resp {
+ network_transaction_id
+ } else {None})
+ .map_err(|err| {
+ logger::error!(error=?err, "Failed to obtain the network_transaction_id from payment response");
+ })
+ .ok()
+ .flatten();
+
+ let network_transaction_id =
+ if let Some(network_transaction_id) = pm_resp_network_transaction_id {
+ let profile_id = payment_data
+ .payment_intent
+ .profile_id
+ .as_ref()
+ .ok_or(errors::ApiErrorResponse::ResourceIdNotFound)?;
+
+ let pg_agnostic = state
+ .store
+ .find_config_by_key_unwrap_or(
+ &format!("pg_agnostic_mandate_{}", profile_id),
+ Some("false".to_string()),
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("The pg_agnostic config was not found in the DB")?;
+
+ if &pg_agnostic.config == "true" {
+ Some(network_transaction_id)
+ } else {
+ logger::info!(
+ "Skip storing network transaction id as pg_agnostic config is not enabled"
+ );
+ None
}
- _ => None,
- })
- .map_err(|err| {
- logger::error!(error=?err, "Failed to obtain the network_transaction_id from payment response");
- })
- .ok()
- .flatten();
+ } else {
+ None
+ };
let pm_update = if pm.status != common_enums::PaymentMethodStatus::Active
&& pm.status != attempt_status.into()
|
2024-03-18T03:41:18Z
|
## 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 -->
During the MIT process, there needs to be validation to check the off_session field. If set to true, then check if the pg_agnostic_mit config is enabled. If it is, perform a lookup in the payment methods table with the payment_method_id in the MIT payment request for the NRID.
If the confirm call fails, retry across the retry-able connectors specified in the `pg_agnostic_mit` configuration.
If the NRID is not present for that particular payment_method_id, or if the `pg_agnostic_mit` flag is not enabled, call the initial connector with which the CIT was 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 a Merchant account
Create a mca for stripe, adyen or cybersource
Enable the pg_agnostic endpoint
```
curl --location 'https://sandbox.hyperswitch.io/routing/business_profile/:business_profile_id/configs/pg_agnostic_mit' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'Authorization: Bearer JWT_Token' \
--data '{
"enabled": true
}'
```
Create a mandate payment (Setup mandate)
<img width="1107" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/3649e1f4-0e19-4c89-b978-e11120a96b92">
```
{
"amount": 0,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"customer_id": "singh",
"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": "03",
"card_exp_year": "2030",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
"setup_future_usage": "off_session",
"payment_type": "setup_mandate",
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "127.0.0.1",
"user_agent": "amet irure esse"
}
},
"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": "John",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"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": "125.0.0.1"
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {},
"order_details": [
{
"product_name": "Apple iphone 15",
"quantity": 1,
"amount": 0,
"account_name": "transaction_processing"
}
]
}
```
DB screenshot where `network_transaction_id` is stored in the `payment_methods` table

Create a payment with confirm false
<img width="972" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/fce68823-ce21-4353-9908-c19ca4f1f468">
List payment methods for customer
```
curl --location 'http://localhost:8080/customers/:customer_id/payment_methods' \
--header 'Accept: application/json' \
--header 'api-key: api-key'
```
<img width="956" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/c0ea7f9e-3468-41ea-8c13-ee4cba57a293">
Confirm the payment by passing the connector as stripe in routing
```
{
"amount": 300,
"currency": "USD",
"confirm": false,
"customer_id": "cyb111",
"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",
"off_session": true,
"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"
}
},
"connector_metadata": {
"noon": {
"order_category": "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": "125.0.0.1"
}
}
```
```
curl --location 'http://localhost:8080/payments/{{payment_id}}/confirm' \
--header 'api-key: api-key' \
--header 'Content-Type: application/json' \
--data '{
"payment_token": "payment_token",
"client_secret": "client_secret",
"payment_method": "card"
}'
```
<img width="1021" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/d8e496ba-90e7-431e-8877-a0aef6c6da28">
## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
63d2b6855acee1adeae2efff10f424e056af0bcb
|
|
juspay/hyperswitch
|
juspay__hyperswitch-3994
|
Bug: Use NRID in recurring payments if the merchant config is enabled
During the MIT process, there needs to be validation to check the off_session field. If set to true, then check if the `pg_agnostic_mit` config is enabled. If it is, perform a lookup in the payment methods table with the `payment_method_id` in the MIT payment request for the NRID. Retrieve the card details from the locker for the specific `payment_method_id`. Make the confirm call to the connector decided by routing.
If the confirm call fails, retry across the retry-able connectors specified in the pg_agnostic_mit configuration.
If the NRID is not present for that particular `payment_method_id`, or if the `pg_agnostic_mit` flag is not enabled, call the initial connector with which the CIT was performed.
|
diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs
index 45aeb1e9074..19a37ab0fb7 100644
--- a/crates/router/src/connector/stripe/transformers.rs
+++ b/crates/router/src/connector/stripe/transformers.rs
@@ -136,6 +136,7 @@ pub struct PaymentIntentRequest {
#[serde(flatten)]
pub payment_data: Option<StripePaymentMethodData>,
pub capture_method: StripeCaptureMethod,
+ #[serde(flatten)]
pub payment_method_options: Option<StripePaymentMethodOptions>, // For mandate txns using network_txns_id, needs to be validated
pub setup_future_usage: Option<enums::FutureUsage>,
pub off_session: Option<bool>,
@@ -189,9 +190,9 @@ pub struct StripeCardData {
#[serde(rename = "payment_method_data[card][exp_year]")]
pub payment_method_data_card_exp_year: Secret<String>,
#[serde(rename = "payment_method_data[card][cvc]")]
- pub payment_method_data_card_cvc: Secret<String>,
+ pub payment_method_data_card_cvc: Option<Secret<String>>,
#[serde(rename = "payment_method_options[card][request_three_d_secure]")]
- pub payment_method_auth_type: Auth3ds,
+ pub payment_method_auth_type: Option<Auth3ds>,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct StripePayLaterData {
@@ -1498,8 +1499,8 @@ impl TryFrom<(&domain::Card, Auth3ds)> for StripePaymentMethodData {
payment_method_data_card_number: card.card_number.clone(),
payment_method_data_card_exp_month: card.card_exp_month.clone(),
payment_method_data_card_exp_year: card.card_exp_year.clone(),
- payment_method_data_card_cvc: card.card_cvc.clone(),
- payment_method_auth_type,
+ payment_method_data_card_cvc: Some(card.card_cvc.clone()),
+ payment_method_auth_type: Some(payment_method_auth_type),
}))
}
}
@@ -1821,7 +1822,44 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentIntentRequest {
network_transaction_id: Secret::new(network_transaction_id),
}),
});
- (None, None, StripeBillingAddress::default(), None)
+
+ let payment_data = match item.request.payment_method_data {
+ domain::payments::PaymentMethodData::Card(ref card) => {
+ StripePaymentMethodData::Card(StripeCardData {
+ payment_method_data_type: StripePaymentMethodType::Card,
+ payment_method_data_card_number: card.card_number.clone(),
+ payment_method_data_card_exp_month: card.card_exp_month.clone(),
+ payment_method_data_card_exp_year: card.card_exp_year.clone(),
+ payment_method_data_card_cvc: None,
+ payment_method_auth_type: None,
+ })
+ }
+ domain::payments::PaymentMethodData::CardRedirect(_)
+ | domain::payments::PaymentMethodData::Wallet(_)
+ | domain::payments::PaymentMethodData::PayLater(_)
+ | domain::payments::PaymentMethodData::BankRedirect(_)
+ | domain::payments::PaymentMethodData::BankDebit(_)
+ | domain::payments::PaymentMethodData::BankTransfer(_)
+ | domain::payments::PaymentMethodData::Crypto(_)
+ | domain::payments::PaymentMethodData::MandatePayment
+ | domain::payments::PaymentMethodData::Reward
+ | domain::payments::PaymentMethodData::Upi(_)
+ | domain::payments::PaymentMethodData::Voucher(_)
+ | domain::payments::PaymentMethodData::GiftCard(_)
+ | domain::payments::PaymentMethodData::CardToken(_) => {
+ Err(errors::ConnectorError::NotSupported {
+ message: "Network tokenization for payment method".to_string(),
+ connector: "Stripe",
+ })?
+ }
+ };
+
+ (
+ Some(payment_data),
+ None,
+ StripeBillingAddress::default(),
+ None,
+ )
}
_ => {
let (payment_method_data, payment_method_type, billing_address) =
@@ -3105,10 +3143,13 @@ impl TryFrom<&types::PaymentsCancelRouterData> for CancelRequest {
#[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)]
#[non_exhaustive]
#[serde(rename_all = "snake_case")]
+#[serde(untagged)]
pub enum StripePaymentMethodOptions {
Card {
mandate_options: Option<StripeMandateOptions>,
+ #[serde(rename = "payment_method_options[card][network_transaction_id]")]
network_transaction_id: Option<Secret<String>>,
+ #[serde(flatten)]
mit_exemption: Option<MitExemption>, // To be used for MIT mandate txns
},
Klarna {},
@@ -3139,6 +3180,7 @@ pub enum StripePaymentMethodOptions {
#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
pub struct MitExemption {
+ #[serde(rename = "payment_method_options[card][mit_exemption][network_transaction_id]")]
pub network_transaction_id: Secret<String>,
}
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index e7ec99f61b6..22f7cb311c6 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -2929,10 +2929,12 @@ where
.attach_printable("Invalid connector name received")?;
return decide_multiplex_connector_for_normal_or_recurring_payment(
+ &state,
payment_data,
routing_data,
connector_data,
- );
+ )
+ .await;
}
if let Some(ref routing_algorithm) = routing_data.routing_info.algorithm {
@@ -2983,10 +2985,12 @@ where
.attach_printable("Invalid connector name received")?;
return decide_multiplex_connector_for_normal_or_recurring_payment(
+ &state,
payment_data,
routing_data,
connector_data,
- );
+ )
+ .await;
}
route_connector_v1(
@@ -3001,7 +3005,8 @@ where
.await
}
-pub fn decide_multiplex_connector_for_normal_or_recurring_payment<F: Clone>(
+pub async fn decide_multiplex_connector_for_normal_or_recurring_payment<F: Clone>(
+ state: &AppState,
payment_data: &mut PaymentData<F>,
routing_data: &mut storage::RoutingData,
connectors: Vec<api::ConnectorData>,
@@ -3010,9 +3015,11 @@ pub fn decide_multiplex_connector_for_normal_or_recurring_payment<F: Clone>(
payment_data.payment_intent.setup_future_usage,
payment_data.token_data.as_ref(),
payment_data.recurring_details.as_ref(),
+ payment_data.payment_intent.off_session,
) {
- (Some(storage_enums::FutureUsage::OffSession), Some(_), None)
- | (None, None, Some(RecurringDetails::PaymentMethodId(_))) => {
+ (Some(storage_enums::FutureUsage::OffSession), Some(_), None, None)
+ | (None, None, Some(RecurringDetails::PaymentMethodId(_)), Some(true))
+ | (None, Some(_), None, Some(true)) => {
logger::debug!("performing routing for token-based MIT flow");
let payment_method_info = payment_data
@@ -3020,32 +3027,108 @@ pub fn decide_multiplex_connector_for_normal_or_recurring_payment<F: Clone>(
.as_ref()
.get_required_value("payment_method_info")?;
- let connector_mandate_details = payment_method_info
- .connector_mandate_details
- .clone()
- .map(|details| {
- details.parse_value::<storage::PaymentsMandateReference>("connector_mandate_details")
- })
- .transpose()
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("unable to deserialize connector mandate details")?
- .get_required_value("connector_mandate_details")
- .change_context(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)
- .attach_printable("no eligible connector found for token-based MIT flow since there were no connector mandate details")?;
+ let connector_mandate_details = &payment_method_info
+ .connector_mandate_details
+ .clone()
+ .map(|details| {
+ details.parse_value::<storage::PaymentsMandateReference>(
+ "connector_mandate_details",
+ )
+ })
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("unable to deserialize connector mandate details")?;
+
+ let profile_id = payment_data
+ .payment_intent
+ .profile_id
+ .as_ref()
+ .ok_or(errors::ApiErrorResponse::ResourceIdNotFound)?;
+
+ let pg_agnostic = state
+ .store
+ .find_config_by_key_unwrap_or(
+ &format!("pg_agnostic_mandate_{}", profile_id),
+ Some("false".to_string()),
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("The pg_agnostic config was not found in the DB")?;
let mut connector_choice = None;
+
for connector_data in connectors {
- if let Some(merchant_connector_id) = connector_data.merchant_connector_id.as_ref() {
- if let Some(mandate_reference_record) =
- connector_mandate_details.get(merchant_connector_id)
+ let merchant_connector_id = connector_data
+ .merchant_connector_id
+ .as_ref()
+ .ok_or(errors::ApiErrorResponse::InternalServerError)?;
+
+ if is_network_transaction_id_flow(
+ state,
+ &pg_agnostic.config,
+ connector_data.connector_name,
+ payment_method_info,
+ ) {
+ let network_transaction_id = payment_method_info
+ .network_transaction_id
+ .as_ref()
+ .ok_or(errors::ApiErrorResponse::InternalServerError)?;
+
+ let mandate_reference_id =
+ Some(payments_api::MandateReferenceId::NetworkMandateId(
+ network_transaction_id.to_string(),
+ ));
+
+ connector_choice = Some((connector_data, mandate_reference_id.clone()));
+ break;
+ } else if connector_mandate_details
+ .clone()
+ .map(|connector_mandate_details| {
+ connector_mandate_details.contains_key(merchant_connector_id)
+ })
+ .unwrap_or(false)
+ {
+ if let Some(merchant_connector_id) =
+ connector_data.merchant_connector_id.as_ref()
{
- connector_choice = Some((connector_data, mandate_reference_record.clone()));
- break;
+ if let Some(mandate_reference_record) = connector_mandate_details.clone()
+ .get_required_value("connector_mandate_details")
+ .change_context(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)
+ .attach_printable("no eligible connector found for token-based MIT flow since there were no connector mandate details")?
+ .get(merchant_connector_id)
+ {
+ let mandate_reference_id =
+ Some(payments_api::MandateReferenceId::ConnectorMandateId(
+ payments_api::ConnectorMandateReferenceId {
+ connector_mandate_id: Some(
+ mandate_reference_record.connector_mandate_id.clone(),
+ ),
+ payment_method_id: Some(
+ payment_method_info.payment_method_id.clone(),
+ ),
+ update_history: None,
+ },
+ ));
+ payment_data.recurring_mandate_payment_data =
+ Some(RecurringMandatePaymentData {
+ payment_method_type: mandate_reference_record
+ .payment_method_type,
+ original_payment_authorized_amount: mandate_reference_record
+ .original_payment_authorized_amount,
+ original_payment_authorized_currency: mandate_reference_record
+ .original_payment_authorized_currency,
+ });
+
+ connector_choice = Some((connector_data, mandate_reference_id.clone()));
+ break;
+ }
}
+ } else {
+ continue;
}
}
- let (chosen_connector_data, mandate_reference_record) = connector_choice
+ let (chosen_connector_data, mandate_reference_id) = connector_choice
.get_required_value("connector_choice")
.change_context(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)
.attach_printable("no eligible connector found for token-based MIT payment")?;
@@ -3056,26 +3139,16 @@ pub fn decide_multiplex_connector_for_normal_or_recurring_payment<F: Clone>(
routing_data.merchant_connector_id =
chosen_connector_data.merchant_connector_id.clone();
}
+ routing_data.routed_through = Some(chosen_connector_data.connector_name.to_string());
+ #[cfg(feature = "connector_choice_mca_id")]
+ {
+ routing_data.merchant_connector_id =
+ chosen_connector_data.merchant_connector_id.clone();
+ }
payment_data.mandate_id = Some(payments_api::MandateIds {
mandate_id: None,
- mandate_reference_id: Some(payments_api::MandateReferenceId::ConnectorMandateId(
- payments_api::ConnectorMandateReferenceId {
- connector_mandate_id: Some(
- mandate_reference_record.connector_mandate_id.clone(),
- ),
- payment_method_id: Some(payment_method_info.payment_method_id.clone()),
- update_history: None,
- },
- )),
- });
-
- payment_data.recurring_mandate_payment_data = Some(RecurringMandatePaymentData {
- payment_method_type: mandate_reference_record.payment_method_type,
- original_payment_authorized_amount: mandate_reference_record
- .original_payment_authorized_amount,
- original_payment_authorized_currency: mandate_reference_record
- .original_payment_authorized_currency,
+ mandate_reference_id,
});
Ok(api::ConnectorCallType::PreDetermined(chosen_connector_data))
@@ -3098,6 +3171,23 @@ pub fn decide_multiplex_connector_for_normal_or_recurring_payment<F: Clone>(
}
}
+pub fn is_network_transaction_id_flow(
+ state: &AppState,
+ pg_agnostic: &String,
+ connector: enums::Connector,
+ payment_method_info: &storage::PaymentMethod,
+) -> bool {
+ let ntid_supported_connectors = &state
+ .conf
+ .network_transaction_id_supported_connectors
+ .connector_list;
+
+ pg_agnostic == "true"
+ && payment_method_info.payment_method == storage_enums::PaymentMethod::Card
+ && ntid_supported_connectors.contains(&connector)
+ && payment_method_info.network_transaction_id.is_some()
+}
+
pub fn should_add_task_to_process_tracker<F: Clone>(payment_data: &PaymentData<F>) -> bool {
let connector = payment_data.payment_attempt.connector.as_deref();
@@ -3315,10 +3405,12 @@ where
match transaction_data {
TransactionData::Payment(payment_data) => {
decide_multiplex_connector_for_normal_or_recurring_payment(
+ state,
payment_data,
routing_data,
connector_data,
)
+ .await
}
#[cfg(feature = "payouts")]
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index 4eac9c1f4de..5214ce3f7a7 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -413,8 +413,11 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
payment_attempt.payment_method = payment_method.or(payment_attempt.payment_method);
payment_attempt.browser_info = browser_info;
- payment_attempt.payment_method_type =
- payment_method_type.or(payment_attempt.payment_method_type);
+ payment_attempt.payment_method_type = payment_method_type
+ .or(payment_attempt.payment_method_type)
+ .or(payment_method_info
+ .as_ref()
+ .and_then(|pm_info| pm_info.payment_method_type));
payment_attempt.payment_experience = request
.payment_experience
diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs
index f418b660380..70cf702311d 100644
--- a/crates/router/src/core/payments/operations/payment_response.rs
+++ b/crates/router/src/core/payments/operations/payment_response.rs
@@ -972,18 +972,46 @@ async fn update_payment_method_status_and_ntid<F: Clone>(
.find_payment_method(id)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
- let network_transaction_id = payment_response
- .map(|resp| match resp {
- crate::types::PaymentsResponseData::TransactionResponse { network_txn_id, .. } => {
- network_txn_id.to_owned()
+
+ let pm_resp_network_transaction_id = payment_response
+ .map(|resp| if let types::PaymentsResponseData::TransactionResponse { network_txn_id: network_transaction_id, .. } = resp {
+ network_transaction_id
+ } else {None})
+ .map_err(|err| {
+ logger::error!(error=?err, "Failed to obtain the network_transaction_id from payment response");
+ })
+ .ok()
+ .flatten();
+
+ let network_transaction_id =
+ if let Some(network_transaction_id) = pm_resp_network_transaction_id {
+ let profile_id = payment_data
+ .payment_intent
+ .profile_id
+ .as_ref()
+ .ok_or(errors::ApiErrorResponse::ResourceIdNotFound)?;
+
+ let pg_agnostic = state
+ .store
+ .find_config_by_key_unwrap_or(
+ &format!("pg_agnostic_mandate_{}", profile_id),
+ Some("false".to_string()),
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("The pg_agnostic config was not found in the DB")?;
+
+ if &pg_agnostic.config == "true" {
+ Some(network_transaction_id)
+ } else {
+ logger::info!(
+ "Skip storing network transaction id as pg_agnostic config is not enabled"
+ );
+ None
}
- _ => None,
- })
- .map_err(|err| {
- logger::error!(error=?err, "Failed to obtain the network_transaction_id from payment response");
- })
- .ok()
- .flatten();
+ } else {
+ None
+ };
let pm_update = if pm.status != common_enums::PaymentMethodStatus::Active
&& pm.status != attempt_status.into()
|
2024-03-18T03:41:18Z
|
## 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 -->
During the MIT process, there needs to be validation to check the off_session field. If set to true, then check if the pg_agnostic_mit config is enabled. If it is, perform a lookup in the payment methods table with the payment_method_id in the MIT payment request for the NRID.
If the confirm call fails, retry across the retry-able connectors specified in the `pg_agnostic_mit` configuration.
If the NRID is not present for that particular payment_method_id, or if the `pg_agnostic_mit` flag is not enabled, call the initial connector with which the CIT was 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 a Merchant account
Create a mca for stripe, adyen or cybersource
Enable the pg_agnostic endpoint
```
curl --location 'https://sandbox.hyperswitch.io/routing/business_profile/:business_profile_id/configs/pg_agnostic_mit' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'Authorization: Bearer JWT_Token' \
--data '{
"enabled": true
}'
```
Create a mandate payment (Setup mandate)
<img width="1107" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/3649e1f4-0e19-4c89-b978-e11120a96b92">
```
{
"amount": 0,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"customer_id": "singh",
"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": "03",
"card_exp_year": "2030",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
"setup_future_usage": "off_session",
"payment_type": "setup_mandate",
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "127.0.0.1",
"user_agent": "amet irure esse"
}
},
"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": "John",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"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": "125.0.0.1"
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {},
"order_details": [
{
"product_name": "Apple iphone 15",
"quantity": 1,
"amount": 0,
"account_name": "transaction_processing"
}
]
}
```
DB screenshot where `network_transaction_id` is stored in the `payment_methods` table

Create a payment with confirm false
<img width="972" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/fce68823-ce21-4353-9908-c19ca4f1f468">
List payment methods for customer
```
curl --location 'http://localhost:8080/customers/:customer_id/payment_methods' \
--header 'Accept: application/json' \
--header 'api-key: api-key'
```
<img width="956" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/c0ea7f9e-3468-41ea-8c13-ee4cba57a293">
Confirm the payment by passing the connector as stripe in routing
```
{
"amount": 300,
"currency": "USD",
"confirm": false,
"customer_id": "cyb111",
"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",
"off_session": true,
"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"
}
},
"connector_metadata": {
"noon": {
"order_category": "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": "125.0.0.1"
}
}
```
```
curl --location 'http://localhost:8080/payments/{{payment_id}}/confirm' \
--header 'api-key: api-key' \
--header 'Content-Type: application/json' \
--data '{
"payment_token": "payment_token",
"client_secret": "client_secret",
"payment_method": "card"
}'
```
<img width="1021" alt="image" src="https://github.com/juspay/hyperswitch/assets/83439957/d8e496ba-90e7-431e-8877-a0aef6c6da28">
## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
63d2b6855acee1adeae2efff10f424e056af0bcb
|
|
juspay/hyperswitch
|
juspay__hyperswitch-3991
|
Bug: Store Network Reference ID against the Payment Method ID for all off-session payments
During the CIT there needs to be a validation which check for the `setup_future_usage` field, if it is set to `off_session` the NRID returned from the connector needs to be stored against the particular `payment_method_id` in the `network_transaction_id` column of the `payment_methods` table.
|
diff --git a/crates/diesel_models/src/payment_method.rs b/crates/diesel_models/src/payment_method.rs
index 7e8dcb639c3..7c28f4cd281 100644
--- a/crates/diesel_models/src/payment_method.rs
+++ b/crates/diesel_models/src/payment_method.rs
@@ -126,6 +126,10 @@ pub enum PaymentMethodUpdate {
LastUsedUpdate {
last_used_at: PrimitiveDateTime,
},
+ NetworkTransactionIdAndStatusUpdate {
+ network_transaction_id: Option<String>,
+ status: Option<storage_enums::PaymentMethodStatus>,
+ },
StatusUpdate {
status: Option<storage_enums::PaymentMethodStatus>,
},
@@ -140,6 +144,7 @@ pub struct PaymentMethodUpdateInternal {
metadata: Option<serde_json::Value>,
payment_method_data: Option<Encryption>,
last_used_at: Option<PrimitiveDateTime>,
+ network_transaction_id: Option<String>,
status: Option<storage_enums::PaymentMethodStatus>,
connector_mandate_details: Option<serde_json::Value>,
}
@@ -159,6 +164,7 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
metadata,
payment_method_data: None,
last_used_at: None,
+ network_transaction_id: None,
status: None,
connector_mandate_details: None,
},
@@ -168,6 +174,7 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
metadata: None,
payment_method_data,
last_used_at: None,
+ network_transaction_id: None,
status: None,
connector_mandate_details: None,
},
@@ -175,13 +182,26 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
metadata: None,
payment_method_data: None,
last_used_at: Some(last_used_at),
+ network_transaction_id: None,
status: None,
connector_mandate_details: None,
},
+ PaymentMethodUpdate::NetworkTransactionIdAndStatusUpdate {
+ network_transaction_id,
+ status,
+ } => Self {
+ metadata: None,
+ payment_method_data: None,
+ last_used_at: None,
+ network_transaction_id,
+ status,
+ connector_mandate_details: None,
+ },
PaymentMethodUpdate::StatusUpdate { status } => Self {
metadata: None,
payment_method_data: None,
last_used_at: None,
+ network_transaction_id: None,
status,
connector_mandate_details: None,
},
@@ -193,6 +213,7 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal {
last_used_at: None,
status: None,
connector_mandate_details,
+ network_transaction_id: None,
},
}
}
diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs
index 7edf28f2c38..45aeb1e9074 100644
--- a/crates/router/src/connector/stripe/transformers.rs
+++ b/crates/router/src/connector/stripe/transformers.rs
@@ -2231,6 +2231,7 @@ impl Deref for PaymentIntentSyncResponse {
pub struct StripeAdditionalCardDetails {
checks: Option<Value>,
three_d_secure: Option<Value>,
+ network_transaction_id: Option<String>,
}
#[derive(Deserialize, Clone, Debug, PartialEq, Eq, Serialize)]
@@ -2685,12 +2686,24 @@ impl<F, T>
item.response.id.clone(),
))
} else {
+ let network_transaction_id = match item.response.latest_attempt {
+ Some(LatestAttempt::PaymentIntentAttempt(attempt)) => attempt
+ .payment_method_details
+ .and_then(|payment_method_details| match payment_method_details {
+ StripePaymentMethodDetailsResponse::Card { card } => {
+ card.network_transaction_id
+ }
+ _ => None,
+ }),
+ _ => None,
+ };
+
Ok(types::PaymentsResponseData::TransactionResponse {
resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data,
mandate_reference,
connector_metadata: None,
- network_txn_id: Option::foreign_from(item.response.latest_attempt),
+ network_txn_id: network_transaction_id,
connector_response_reference_id: Some(item.response.id),
incremental_authorization_allowed: None,
})
@@ -3140,6 +3153,7 @@ pub struct LatestPaymentAttempt {
pub payment_method_options: Option<StripePaymentMethodOptions>,
pub payment_method_details: Option<StripePaymentMethodDetailsResponse>,
}
+
// #[derive(Deserialize, Debug, Clone, Eq, PartialEq)]
// pub struct Card
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug, Default, Eq, PartialEq)]
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index 64346a94a9d..d94864c75b5 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -87,6 +87,7 @@ pub async fn create_payment_method(
payment_method_data: Option<Encryption>,
key_store: &domain::MerchantKeyStore,
connector_mandate_details: Option<serde_json::Value>,
+ network_transaction_id: Option<String>,
) -> errors::CustomResult<storage::PaymentMethod, errors::ApiErrorResponse> {
let customer = db
.find_customer_by_customer_id_merchant_id(customer_id, merchant_id, key_store)
@@ -107,6 +108,7 @@ pub async fn create_payment_method(
payment_method_data,
connector_mandate_details,
customer_acceptance: customer_acceptance.map(masking::Secret::new),
+ network_transaction_id: network_transaction_id.to_owned(),
..storage::PaymentMethodNew::default()
})
.await
@@ -205,6 +207,7 @@ pub async fn get_or_insert_payment_method(
None,
locker_id,
None,
+ None,
)
.await
} else {
@@ -392,6 +395,7 @@ pub async fn add_payment_method(
None,
locker_id,
None,
+ None,
)
.await?;
}
@@ -412,6 +416,7 @@ pub async fn insert_payment_method(
customer_acceptance: Option<serde_json::Value>,
locker_id: Option<String>,
connector_mandate_details: Option<serde_json::Value>,
+ network_transaction_id: Option<String>,
) -> errors::RouterResult<diesel_models::PaymentMethod> {
let pm_card_details = resp
.card
@@ -430,6 +435,7 @@ pub async fn insert_payment_method(
pm_data_encrypted,
key_store,
connector_mandate_details,
+ network_transaction_id,
)
.await
}
diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs
index 66f35e63b2c..f418b660380 100644
--- a/crates/router/src/core/payments/operations/payment_response.rs
+++ b/crates/router/src/core/payments/operations/payment_response.rs
@@ -7,7 +7,7 @@ use data_models::payments::payment_attempt::PaymentAttempt;
use error_stack::{report, ResultExt};
use futures::FutureExt;
use router_derive;
-use router_env::{instrument, tracing};
+use router_env::{instrument, logger, tracing};
use storage_impl::DataModelExt;
use tracing_futures::Instrument;
@@ -34,7 +34,7 @@ use crate::{
self, api,
storage::{self, enums},
transformers::{ForeignFrom, ForeignTryFrom},
- CaptureSyncResponse,
+ CaptureSyncResponse, ErrorResponse,
},
utils,
};
@@ -833,7 +833,7 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
};
let amount_captured = get_total_amount_captured(
- router_data.request,
+ &router_data.request,
router_data.amount_captured,
router_data.status,
&payment_data,
@@ -862,7 +862,13 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
},
};
- update_payment_method_status(state, &mut payment_data, router_data.status).await?;
+ update_payment_method_status_and_ntid(
+ state,
+ &mut payment_data,
+ router_data.status,
+ router_data.response.clone(),
+ )
+ .await?;
let m_db = state.clone().store;
let m_payment_data_payment_intent = payment_data.payment_intent.clone();
let m_payment_intent_update = payment_intent_update.clone();
@@ -954,10 +960,11 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
Ok(payment_data)
}
-async fn update_payment_method_status<F: Clone>(
+async fn update_payment_method_status_and_ntid<F: Clone>(
state: &AppState,
payment_data: &mut PaymentData<F>,
attempt_status: common_enums::AttemptStatus,
+ payment_response: Result<types::PaymentsResponseData, ErrorResponse>,
) -> RouterResult<()> {
if let Some(id) = &payment_data.payment_attempt.payment_method_id {
let pm = state
@@ -965,8 +972,20 @@ async fn update_payment_method_status<F: Clone>(
.find_payment_method(id)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
+ let network_transaction_id = payment_response
+ .map(|resp| match resp {
+ crate::types::PaymentsResponseData::TransactionResponse { network_txn_id, .. } => {
+ network_txn_id.to_owned()
+ }
+ _ => None,
+ })
+ .map_err(|err| {
+ logger::error!(error=?err, "Failed to obtain the network_transaction_id from payment response");
+ })
+ .ok()
+ .flatten();
- if pm.status != common_enums::PaymentMethodStatus::Active
+ let pm_update = if pm.status != common_enums::PaymentMethodStatus::Active
&& pm.status != attempt_status.into()
{
let updated_pm_status = common_enums::PaymentMethodStatus::from(attempt_status);
@@ -975,16 +994,23 @@ async fn update_payment_method_status<F: Clone>(
.payment_method_info
.as_mut()
.map(|info| info.status = updated_pm_status);
- let pm_update = storage::PaymentMethodUpdate::StatusUpdate {
+ storage::PaymentMethodUpdate::NetworkTransactionIdAndStatusUpdate {
+ network_transaction_id,
status: Some(updated_pm_status),
- };
- state
- .store
- .update_payment_method(pm, pm_update)
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to update payment method in db")?;
- }
+ }
+ } else {
+ storage::PaymentMethodUpdate::NetworkTransactionIdAndStatusUpdate {
+ network_transaction_id,
+ status: None,
+ }
+ };
+
+ state
+ .store
+ .update_payment_method(pm, pm_update)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to update payment method in db")?;
};
Ok(())
}
@@ -1043,7 +1069,7 @@ fn get_capture_update_for_unmapped_capture_responses(
}
fn get_total_amount_captured<F: Clone, T: types::Capturable>(
- request: T,
+ request: &T,
amount_captured: Option<i64>,
router_data_status: enums::AttemptStatus,
payment_data: &PaymentData<F>,
diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs
index 4d616146908..7a8f487d73a 100644
--- a/crates/router/src/core/payments/operations/payment_status.rs
+++ b/crates/router/src/core/payments/operations/payment_status.rs
@@ -399,6 +399,18 @@ async fn get_tracker_for_sync<
.to_not_found_response(errors::ApiErrorResponse::BusinessProfileNotFound {
id: profile_id.to_string(),
})?;
+ let payment_method_info =
+ if let Some(ref payment_method_id) = payment_attempt.payment_method_id.clone() {
+ Some(
+ db.find_payment_method(payment_method_id)
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)
+ .attach_printable("error retrieving payment method from DB")?,
+ )
+ } else {
+ None
+ };
+
let merchant_id = payment_intent.merchant_id.clone();
let authentication = payment_attempt.authentication_id.clone().async_map(|authentication_id| async move {
db.find_authentication_by_merchant_id_authentication_id(
@@ -436,7 +448,7 @@ async fn get_tracker_for_sync<
token_data: None,
confirm: Some(request.force_sync),
payment_method_data: None,
- payment_method_info: None,
+ payment_method_info,
force_sync: Some(
request.force_sync
&& (helpers::check_force_psync_precondition(&payment_attempt.status)
diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs
index 3941fad5a42..47cd1cd9eb7 100644
--- a/crates/router/src/core/payments/tokenization.rs
+++ b/crates/router/src/core/payments/tokenization.rs
@@ -57,6 +57,13 @@ where
.map(|token_filter| token_filter.long_lived_token)
.unwrap_or(false);
+ let network_transaction_id = match responses.clone() {
+ types::PaymentsResponseData::TransactionResponse { network_txn_id, .. } => {
+ network_txn_id
+ }
+ _ => None,
+ };
+
let connector_token = if token_store {
let tokens = resp
.payment_method_token
@@ -255,6 +262,7 @@ where
pm_data_encrypted,
key_store,
connector_mandate_details,
+ network_transaction_id,
)
.await
} else {
@@ -337,6 +345,7 @@ where
customer_acceptance,
locker_id,
connector_mandate_details,
+ network_transaction_id,
)
.await
} else {
@@ -459,6 +468,7 @@ where
pm_data_encrypted,
key_store,
connector_mandate_details,
+ network_transaction_id,
)
.await?;
}
diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs
index 1a94186a86f..6efe6ee9a77 100644
--- a/crates/router/src/core/payouts/helpers.rs
+++ b/crates/router/src/core/payouts/helpers.rs
@@ -13,8 +13,8 @@ use crate::{
core::{
errors::{self, RouterResult},
payment_methods::{
- cards, transformers,
- transformers::{StoreCardReq, StoreGenericReq, StoreLockerReq},
+ cards,
+ transformers::{self, StoreCardReq, StoreGenericReq, StoreLockerReq},
vault,
},
payments::{
@@ -389,6 +389,7 @@ pub async fn save_payout_data_to_locker(
card_details_encrypted,
key_store,
None,
+ None,
)
.await?;
|
2024-03-12T08:10:34Z
|
## 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 -->
During the CIT there needs to be a validation which check for the setup_future_usage field, if it is set to off_session the NRID returned from the connector needs to be stored against the particular payment_method_id in the network_transaction_id column of the payment_methods table.
### 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 mca for stripe, adyen or cybersource
Create a mandate payment (Setup mandate)
```
{
"amount": 0,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"customer_id": "singh",
"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": "03",
"card_exp_year": "2030",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
"setup_future_usage": "off_session",
"payment_type": "setup_mandate",
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "127.0.0.1",
"user_agent": "amet irure esse"
}
},
"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": "John",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"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": "125.0.0.1"
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {},
"order_details": [
{
"product_name": "Apple iphone 15",
"quantity": 1,
"amount": 0,
"account_name": "transaction_processing"
}
]
}
```
Once the mandate is successful the network_transaction_id is stored as below
`network_transaction_id` being stored in `payment_method` table

## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
ad1f74f2c3da9e2a40e8646d8af07081e7ac3ee1
|
|
juspay/hyperswitch
|
juspay__hyperswitch-3987
|
Bug: feat: get specific user role details api
Currently frontend is using the user list api to get the details of the users in a particular merchant account.
If somebody is in a user details page and refreshes, FE will again call list api to get the details as there is no api to get the details of a specific user.
|
diff --git a/crates/api_models/src/events/user.rs b/crates/api_models/src/events/user.rs
index ec3e2dce9b2..4ef04981572 100644
--- a/crates/api_models/src/events/user.rs
+++ b/crates/api_models/src/events/user.rs
@@ -11,11 +11,11 @@ use crate::user::{
GetMetaDataRequest, GetMetaDataResponse, GetMultipleMetaDataPayload, SetMetaDataRequest,
},
AcceptInviteFromEmailRequest, AuthorizeResponse, ChangePasswordRequest, ConnectAccountRequest,
- CreateInternalUserRequest, DashboardEntryResponse, ForgotPasswordRequest, GetUsersResponse,
- InviteUserRequest, InviteUserResponse, ReInviteUserRequest, ResetPasswordRequest,
- SendVerifyEmailRequest, SignInResponse, SignUpRequest, SignUpWithMerchantIdRequest,
- SwitchMerchantIdRequest, UpdateUserAccountDetailsRequest, UserMerchantCreate,
- VerifyEmailRequest,
+ CreateInternalUserRequest, DashboardEntryResponse, ForgotPasswordRequest,
+ GetUserDetailsRequest, GetUserDetailsResponse, InviteUserRequest, InviteUserResponse,
+ ListUsersResponse, ReInviteUserRequest, ResetPasswordRequest, SendVerifyEmailRequest,
+ SignInResponse, SignUpRequest, SignUpWithMerchantIdRequest, SwitchMerchantIdRequest,
+ UpdateUserAccountDetailsRequest, UserMerchantCreate, VerifyEmailRequest,
};
impl ApiEventMetric for DashboardEntryResponse {
@@ -48,7 +48,7 @@ common_utils::impl_misc_api_event_type!(
SwitchMerchantIdRequest,
CreateInternalUserRequest,
UserMerchantCreate,
- GetUsersResponse,
+ ListUsersResponse,
AuthorizeResponse,
ConnectAccountRequest,
ForgotPasswordRequest,
@@ -60,7 +60,9 @@ common_utils::impl_misc_api_event_type!(
SendVerifyEmailRequest,
AcceptInviteFromEmailRequest,
SignInResponse,
- UpdateUserAccountDetailsRequest
+ UpdateUserAccountDetailsRequest,
+ GetUserDetailsRequest,
+ GetUserDetailsResponse
);
#[cfg(feature = "dummy_connector")]
diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs
index 8f77f72aad5..0db711f5eca 100644
--- a/crates/api_models/src/user.rs
+++ b/crates/api_models/src/user.rs
@@ -1,3 +1,4 @@
+use common_enums::{PermissionGroup, RoleScope};
use common_utils::{crypto::OptionalEncryptableName, pii};
use masking::Secret;
@@ -143,7 +144,7 @@ pub struct UserMerchantCreate {
}
#[derive(Debug, serde::Serialize)]
-pub struct GetUsersResponse(pub Vec<UserDetails>);
+pub struct ListUsersResponse(pub Vec<UserDetails>);
#[derive(Debug, serde::Serialize)]
pub struct UserDetails {
@@ -156,6 +157,24 @@ pub struct UserDetails {
pub last_modified_at: time::PrimitiveDateTime,
}
+#[derive(Debug, serde::Deserialize, serde::Serialize)]
+pub struct GetUserDetailsRequest {
+ pub email: pii::Email,
+}
+
+#[derive(Debug, serde::Serialize)]
+pub struct GetUserDetailsResponse {
+ pub email: pii::Email,
+ pub name: Secret<String>,
+ pub role_id: String,
+ pub role_name: String,
+ pub status: UserStatus,
+ #[serde(with = "common_utils::custom_serde::iso8601")]
+ pub last_modified_at: time::PrimitiveDateTime,
+ pub groups: Vec<PermissionGroup>,
+ pub role_scope: RoleScope,
+}
+
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct VerifyEmailRequest {
pub token: Secret<String>,
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index b8b8cbd24c7..6516022cfd7 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -1193,10 +1193,53 @@ pub async fn list_merchant_ids_for_user(
))
}
-pub async fn get_users_for_merchant_account(
+pub async fn get_user_details_in_merchant_account(
state: AppState,
user_from_token: auth::UserFromToken,
-) -> UserResponse<user_api::GetUsersResponse> {
+ request: user_api::GetUserDetailsRequest,
+) -> UserResponse<user_api::GetUserDetailsResponse> {
+ let required_user = utils::user::get_user_from_db_by_email(&state, request.email.try_into()?)
+ .await
+ .to_not_found_response(UserErrors::InvalidRoleOperation)?;
+
+ let required_user_role = state
+ .store
+ .find_user_role_by_user_id_merchant_id(
+ required_user.get_user_id(),
+ &user_from_token.merchant_id,
+ )
+ .await
+ .to_not_found_response(UserErrors::InvalidRoleOperation)
+ .attach_printable("User not found in the merchant account")?;
+
+ let role_info = roles::RoleInfo::from_role_id(
+ &state,
+ &required_user_role.role_id,
+ &user_from_token.merchant_id,
+ &user_from_token.org_id,
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)
+ .attach_printable("User role exists but the corresponding role doesn't")?;
+
+ Ok(ApplicationResponse::Json(
+ user_api::GetUserDetailsResponse {
+ email: required_user.get_email(),
+ name: required_user.get_name(),
+ role_id: role_info.get_role_id().to_string(),
+ role_name: role_info.get_role_name().to_string(),
+ status: required_user_role.status.foreign_into(),
+ last_modified_at: required_user_role.last_modified,
+ groups: role_info.get_permission_groups().to_vec(),
+ role_scope: role_info.get_scope(),
+ },
+ ))
+}
+
+pub async fn list_users_for_merchant_account(
+ state: AppState,
+ user_from_token: auth::UserFromToken,
+) -> UserResponse<user_api::ListUsersResponse> {
let users_and_user_roles = state
.store
.find_users_and_roles_by_merchant_id(user_from_token.merchant_id.as_str())
@@ -1235,7 +1278,7 @@ pub async fn get_users_for_merchant_account(
})
.collect();
- Ok(ApplicationResponse::Json(user_api::GetUsersResponse(
+ Ok(ApplicationResponse::Json(user_api::ListUsersResponse(
user_details_vec,
)))
}
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 73558c78d7b..b37e034d8db 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1115,7 +1115,10 @@ impl User {
// User management
route = route.service(
web::scope("/user")
- .service(web::resource("/list").route(web::get().to(get_user_details)))
+ .service(web::resource("").route(web::get().to(get_user_role_details)))
+ .service(
+ web::resource("/list").route(web::get().to(list_users_for_merchant_account)),
+ )
.service(web::resource("/invite").route(web::post().to(invite_user)))
.service(
web::resource("/invite_multiple").route(web::post().to(invite_multiple_user)),
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index 9471289a0c8..897b33266b8 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -182,6 +182,7 @@ impl From<Flow> for ApiIdentifier {
| Flow::DeleteSampleData
| Flow::UserMerchantAccountList
| Flow::GetUserDetails
+ | Flow::ListUsersForMerchantAccount
| Flow::ForgotPassword
| Flow::ResetPassword
| Flow::InviteUser
diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs
index 0568b31338b..3c10ce38f9f 100644
--- a/crates/router/src/routes/user.rs
+++ b/crates/router/src/routes/user.rs
@@ -314,14 +314,35 @@ pub async fn list_merchant_ids_for_user(
.await
}
-pub async fn get_user_details(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse {
+pub async fn get_user_role_details(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ payload: web::Query<user_api::GetUserDetailsRequest>,
+) -> HttpResponse {
let flow = Flow::GetUserDetails;
+ Box::pin(api::server_wrap(
+ flow,
+ state.clone(),
+ &req,
+ payload.into_inner(),
+ user_core::get_user_details_in_merchant_account,
+ &auth::JWTAuth(Permission::UsersRead),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
+pub async fn list_users_for_merchant_account(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+) -> HttpResponse {
+ let flow = Flow::ListUsersForMerchantAccount;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
(),
- |state, user, _| user_core::get_users_for_merchant_account(state, user),
+ |state, user, _| user_core::list_users_for_merchant_account(state, user),
&auth::JWTAuth(Permission::UsersRead),
api_locking::LockAction::NotApplicable,
))
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index 62c09c42455..b4adc077af1 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -330,8 +330,10 @@ pub enum Flow {
DeleteSampleData,
/// List merchant accounts for user
UserMerchantAccountList,
- /// Get users for merchant account
+ /// Get details of a user in a merchant account
GetUserDetails,
+ /// List users for merchant account
+ ListUsersForMerchantAccount,
/// PaymentMethodAuth Link token create
PmAuthLinkTokenCreate,
/// PaymentMethodAuth Exchange token create
|
2024-03-06T12:39: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 there is no way to get the details of user and their role directly. This API solves it by taking the email of the user and returns the details.
### 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 [#3987](https://github.com/juspay/hyperswitch/issues/3987)
## 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)?
-->
Postman.
```
curl --location 'http://localhost:8080/user/user?email=user@hyperswitch.io' \
--header 'Authorization: Bearer JWT'
```
```
{
"email": "user email",
"name": "user name",
"role_id": "merchant_view_only",
"role_name": "View Only",
"status": "Active",
"last_modified_at": "2024-03-01T06:23:44.250Z",
"groups": [
"operations_view",
"connectors_view",
"workflows_view",
"analytics_view",
"users_view",
"merchant_details_view"
],
"role_scope": "organization"
}
```
## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
2db39e8bb9af3d55e3d075d77ff8616ee2e15f0a
|
|
juspay/hyperswitch
|
juspay__hyperswitch-3986
|
Bug: Create a new column in PM table to store NRID
**Schema changes**
`network_transaction_id` column needs to be created in the `payment_methods` table to store the NTID / NRID for all the required payment method.
|
diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml
index 77040f79a4a..67dfddd0d55 100644
--- a/config/deployments/integration_test.toml
+++ b/config/deployments/integration_test.toml
@@ -129,6 +129,9 @@ bank_redirect.giropay.connector_list = "adyen,globalpay"
card.credit ={connector_list ="cybersource"}
card.debit = {connector_list ="cybersource"}
+[network_transaction_id_supported_connectors]
+connector_list = "stripe,adyen,cybersource"
+
[multiple_api_version_supported_connectors]
supported_connectors = "braintree"
diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml
index 8ae12dc54a6..03dc7825222 100644
--- a/config/deployments/sandbox.toml
+++ b/config/deployments/sandbox.toml
@@ -128,6 +128,9 @@ bank_redirect.giropay.connector_list = "adyen,globalpay"
card.credit = { connector_list = "cybersource" }
card.debit = { connector_list = "cybersource" }
+[network_transaction_id_supported_connectors]
+connector_list = "stripe,adyen,cybersource"
+
[multiple_api_version_supported_connectors]
supported_connectors = "braintree"
diff --git a/config/development.toml b/config/development.toml
index 8ba5c076071..5cdd5f0b9bf 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -511,6 +511,9 @@ bank_redirect.giropay = { connector_list = "adyen,globalpay" }
card.credit = { connector_list = "cybersource" }
card.debit = { connector_list = "cybersource" }
+[network_transaction_id_supported_connectors]
+connector_list = "stripe,adyen,cybersource"
+
[connector_request_reference_id_config]
merchant_ids_send_payment_id_as_connector_request_id = []
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index eb32b47e3b4..1077bf34c02 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -381,6 +381,9 @@ bank_redirect.giropay = { connector_list = "adyen,globalpay" }
card.credit = { connector_list = "cybersource" }
card.debit = { connector_list = "cybersource" }
+[network_transaction_id_supported_connectors]
+connector_list = "stripe,adyen,cybersource"
+
[connector_customer]
connector_list = "gocardless,stax,stripe"
payout_connector_list = "wise"
diff --git a/crates/diesel_models/src/payment_method.rs b/crates/diesel_models/src/payment_method.rs
index ef153c23a7b..681a57bda87 100644
--- a/crates/diesel_models/src/payment_method.rs
+++ b/crates/diesel_models/src/payment_method.rs
@@ -38,6 +38,7 @@ pub struct PaymentMethod {
pub connector_mandate_details: Option<serde_json::Value>,
pub customer_acceptance: Option<pii::SecretSerdeValue>,
pub status: storage_enums::PaymentMethodStatus,
+ pub network_transaction_id: Option<String>,
}
#[derive(Clone, Debug, Eq, PartialEq, Insertable, router_derive::DebugAsDisplay)]
@@ -69,6 +70,7 @@ pub struct PaymentMethodNew {
pub connector_mandate_details: Option<serde_json::Value>,
pub customer_acceptance: Option<pii::SecretSerdeValue>,
pub status: storage_enums::PaymentMethodStatus,
+ pub network_transaction_id: Option<String>,
}
impl Default for PaymentMethodNew {
@@ -102,6 +104,7 @@ impl Default for PaymentMethodNew {
connector_mandate_details: Option::default(),
customer_acceptance: Option::default(),
status: storage_enums::PaymentMethodStatus::Active,
+ network_transaction_id: Option::default(),
}
}
}
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index 8e8bf48a538..ad30609a770 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -913,6 +913,8 @@ diesel::table! {
customer_acceptance -> Nullable<Jsonb>,
#[max_length = 64]
status -> Varchar,
+ #[max_length = 255]
+ network_transaction_id -> Nullable<Varchar>,
}
}
diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rs
index 6906b5a3e7a..537f6666c5d 100644
--- a/crates/router/src/configs/secrets_transformers.rs
+++ b/crates/router/src/configs/secrets_transformers.rs
@@ -335,6 +335,8 @@ pub(crate) async fn fetch_raw_secrets(
#[cfg(feature = "email")]
email: conf.email,
mandates: conf.mandates,
+ network_transaction_id_supported_connectors: conf
+ .network_transaction_id_supported_connectors,
required_fields: conf.required_fields,
delayed_session_response: conf.delayed_session_response,
webhook_source_verification_call: conf.webhook_source_verification_call,
diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs
index d92812cee40..a0dce991295 100644
--- a/crates/router/src/configs/settings.rs
+++ b/crates/router/src/configs/settings.rs
@@ -91,6 +91,7 @@ pub struct Settings<S: SecretState> {
pub email: EmailSettings,
pub cors: CorsSettings,
pub mandates: Mandates,
+ pub network_transaction_id_supported_connectors: NetworkTransactionIdSupportedConnectors,
pub required_fields: RequiredFields,
pub delayed_session_response: DelayedSessionConfig,
pub webhook_source_verification_call: WebhookSourceVerificationCall,
@@ -251,6 +252,12 @@ pub struct Mandates {
pub update_mandate_supported: SupportedPaymentMethodsForMandate,
}
+#[derive(Debug, Deserialize, Clone, Default)]
+pub struct NetworkTransactionIdSupportedConnectors {
+ #[serde(deserialize_with = "deserialize_hashset")]
+ pub connector_list: HashSet<api_models::enums::Connector>,
+}
+
#[derive(Debug, Deserialize, Clone)]
pub struct SupportedPaymentMethodsForMandate(
pub HashMap<enums::PaymentMethod, SupportedPaymentMethodTypesForMandate>,
diff --git a/crates/router/src/db/payment_method.rs b/crates/router/src/db/payment_method.rs
index 14f650127dd..188eeeddc10 100644
--- a/crates/router/src/db/payment_method.rs
+++ b/crates/router/src/db/payment_method.rs
@@ -275,6 +275,7 @@ impl PaymentMethodInterface for MockDb {
connector_mandate_details: payment_method_new.connector_mandate_details,
customer_acceptance: payment_method_new.customer_acceptance,
status: payment_method_new.status,
+ network_transaction_id: payment_method_new.network_transaction_id,
};
payment_methods.push(payment_method.clone());
Ok(payment_method)
diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml
index 72eb6f25559..a2d2648133b 100644
--- a/loadtest/config/development.toml
+++ b/loadtest/config/development.toml
@@ -277,6 +277,9 @@ wildcard_origin = false
card.credit ={connector_list ="cybersource"}
card.debit = {connector_list ="cybersource"}
+[network_transaction_id_supported_connectors]
+connector_list = "stripe,adyen,cybersource"
+
[analytics]
source = "sqlx"
diff --git a/migrations/2024-03-07-102620_add-network-transaction-id/down.sql b/migrations/2024-03-07-102620_add-network-transaction-id/down.sql
new file mode 100644
index 00000000000..4cf99815a9b
--- /dev/null
+++ b/migrations/2024-03-07-102620_add-network-transaction-id/down.sql
@@ -0,0 +1,3 @@
+-- This file should undo anything in `up.sql`
+
+ALTER TABLE payment_methods DROP COLUMN network_transaction_id;
\ No newline at end of file
diff --git a/migrations/2024-03-07-102620_add-network-transaction-id/up.sql b/migrations/2024-03-07-102620_add-network-transaction-id/up.sql
new file mode 100644
index 00000000000..06b199e6390
--- /dev/null
+++ b/migrations/2024-03-07-102620_add-network-transaction-id/up.sql
@@ -0,0 +1,3 @@
+-- Your SQL goes here
+
+ALTER TABLE payment_methods ADD COLUMN network_transaction_id VARCHAR(255) DEFAULT NULL;
\ No newline at end of file
|
2024-03-07T11:34:54Z
|
## 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 `network_transaction_id` column in the `payment_methods` table as it is required to store the NRID against the respective payment_method_id. This NRID will later be used processor agnostic MITs. This pr also adds application level config (`network_transactoin_id_supported_connectors`) that contains the list of connectors that support the `network_transaction_id`.
### 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)?
-->
columns in the `payment_methods` table

## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
aecf4aeacce33c3dc03e089ef6d62af93e29ca9a
|
|
juspay/hyperswitch
|
juspay__hyperswitch-3983
|
Bug: refactor: kms decrypt analytics config
Add support for kms decrypting the analytics config
|
diff --git a/Cargo.lock b/Cargo.lock
index 60bc557972c..4571d80fd87 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -349,6 +349,7 @@ dependencies = [
"error-stack",
"external_services",
"futures 0.3.28",
+ "hyperswitch_interfaces",
"masking",
"once_cell",
"reqwest",
diff --git a/crates/analytics/Cargo.toml b/crates/analytics/Cargo.toml
index 82ac2dde030..f3e01492135 100644
--- a/crates/analytics/Cargo.toml
+++ b/crates/analytics/Cargo.toml
@@ -11,8 +11,9 @@ edition = "2021"
# First party crates
api_models = { version = "0.1.0", path = "../api_models" , features = ["errors"]}
storage_impl = { version = "0.1.0", path = "../storage_impl", default-features = false }
-common_utils = { version = "0.1.0", path = "../common_utils"}
-external_services = { version = "0.1.0", path = "../external_services", default-features = false}
+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" }
masking = { version = "0.1.0", path = "../masking" }
router_env = { version = "0.1.0", path = "../router_env", features = ["log_extra_implicit_fields", "log_custom_entries_to_extra"] }
diesel_models = { version = "0.1.0", path = "../diesel_models", features = ["kv_store"] }
diff --git a/crates/analytics/src/lib.rs b/crates/analytics/src/lib.rs
index c9752bd27a6..d8de32a732b 100644
--- a/crates/analytics/src/lib.rs
+++ b/crates/analytics/src/lib.rs
@@ -15,7 +15,13 @@ pub mod sdk_events;
mod sqlx;
mod types;
use api_event::metrics::{ApiEventMetric, ApiEventMetricRow};
+use common_utils::errors::CustomResult;
use disputes::metrics::{DisputeMetric, DisputeMetricRow};
+use hyperswitch_interfaces::secrets_interface::{
+ secret_handler::SecretsHandler,
+ secret_state::{RawSecret, SecretStateContainer, SecuredSecret},
+ SecretManagementInterface, SecretsManagementError,
+};
pub use types::AnalyticsDomain;
pub mod lambda_utils;
pub mod utils;
@@ -598,6 +604,51 @@ pub enum AnalyticsConfig {
},
}
+#[async_trait::async_trait]
+impl SecretsHandler for AnalyticsConfig {
+ async fn convert_to_raw_secret(
+ value: SecretStateContainer<Self, SecuredSecret>,
+ secret_management_client: &dyn SecretManagementInterface,
+ ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> {
+ let analytics_config = value.get_inner();
+ let decrypted_password = match analytics_config {
+ // Todo: Perform kms decryption of clickhouse password
+ Self::Clickhouse { .. } => masking::Secret::new(String::default()),
+ Self::Sqlx { sqlx }
+ | Self::CombinedCkh { sqlx, .. }
+ | Self::CombinedSqlx { sqlx, .. } => {
+ secret_management_client
+ .get_secret(sqlx.password.clone())
+ .await?
+ }
+ };
+
+ Ok(value.transition_state(|conf| match conf {
+ Self::Sqlx { sqlx } => Self::Sqlx {
+ sqlx: Database {
+ password: decrypted_password,
+ ..sqlx
+ },
+ },
+ Self::Clickhouse { clickhouse } => Self::Clickhouse { clickhouse },
+ Self::CombinedCkh { sqlx, clickhouse } => Self::CombinedCkh {
+ sqlx: Database {
+ password: decrypted_password,
+ ..sqlx
+ },
+ clickhouse,
+ },
+ Self::CombinedSqlx { sqlx, clickhouse } => Self::CombinedSqlx {
+ sqlx: Database {
+ password: decrypted_password,
+ ..sqlx
+ },
+ clickhouse,
+ },
+ }))
+ }
+}
+
impl Default for AnalyticsConfig {
fn default() -> Self {
Self::Sqlx {
diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rs
index bbcc2b5bceb..f89d1811988 100644
--- a/crates/router/src/configs/secrets_transformers.rs
+++ b/crates/router/src/configs/secrets_transformers.rs
@@ -233,6 +233,13 @@ pub(crate) async fn fetch_raw_secrets(
.await
.expect("Failed to decrypt master database configuration");
+ #[cfg(feature = "olap")]
+ #[allow(clippy::expect_used)]
+ let analytics =
+ analytics::AnalyticsConfig::convert_to_raw_secret(conf.analytics, secret_management_client)
+ .await
+ .expect("Failed to decrypt analytics configuration");
+
#[cfg(feature = "olap")]
#[allow(clippy::expect_used)]
let replica_database =
@@ -342,7 +349,7 @@ pub(crate) async fn fetch_raw_secrets(
temp_locker_enable_config: conf.temp_locker_enable_config,
payment_link: conf.payment_link,
#[cfg(feature = "olap")]
- analytics: conf.analytics,
+ analytics,
#[cfg(feature = "kv_store")]
kv_config: conf.kv_config,
#[cfg(feature = "frm")]
diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs
index 00897951ba8..70a173f1d95 100644
--- a/crates/router/src/configs/settings.rs
+++ b/crates/router/src/configs/settings.rs
@@ -105,7 +105,7 @@ pub struct Settings<S: SecretState> {
pub temp_locker_enable_config: TempLockerEnableConfig,
pub payment_link: PaymentLink,
#[cfg(feature = "olap")]
- pub analytics: AnalyticsConfig,
+ pub analytics: SecretStateContainer<AnalyticsConfig, S>,
#[cfg(feature = "kv_store")]
pub kv_config: KvConfig,
#[cfg(feature = "frm")]
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 1d82bc7539f..798b07d149f 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -200,7 +200,8 @@ impl AppState {
};
#[cfg(feature = "olap")]
- let pool = crate::analytics::AnalyticsProvider::from_conf(&conf.analytics).await;
+ let pool =
+ crate::analytics::AnalyticsProvider::from_conf(conf.analytics.get_inner()).await;
#[cfg(feature = "email")]
let email_client = Arc::new(create_email_client(&conf).await);
|
2024-03-06T11:53:38Z
|
## 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 support for kms decrypting the analytics config
### 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)?
-->
Locally set up aws kms and decryption of analytics config was successful.
Currently Sandbox uses clickhouse setup, so this PR cannot be tested. Can be deployed in custom pod by using Sqlx there.
## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
2db39e8bb9af3d55e3d075d77ff8616ee2e15f0a
|
|
juspay/hyperswitch
|
juspay__hyperswitch-3980
|
Bug: [FEATURE] [AUTHORIZEDOTNET] Pass billing address details
### Feature Description
Billing Address needs to be passed in payments request.
### Possible Implementation
Billing Address needs to be passed in BillTo field of payments request 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 8ba610d66d4..2d6f2e040a4 100644
--- a/crates/router/src/connector/authorizedotnet/transformers.rs
+++ b/crates/router/src/connector/authorizedotnet/transformers.rs
@@ -7,10 +7,17 @@ use masking::{ExposeInterface, PeekInterface, Secret, StrongSecret};
use serde::{Deserialize, Serialize};
use crate::{
- connector::utils::{self, CardData, PaymentsSyncRequestData, RefundsRequestData, WalletData},
+ connector::utils::{
+ self, CardData, PaymentsSyncRequestData, RefundsRequestData, RouterData, WalletData,
+ },
core::errors,
services,
- types::{self, api, storage::enums, transformers::ForeignFrom},
+ types::{
+ self,
+ api::{self, enums as api_enums},
+ storage::enums,
+ transformers::ForeignFrom,
+ },
utils::OptionExt,
};
@@ -231,6 +238,8 @@ struct TransactionRequest {
amount: f64,
currency_code: String,
payment: PaymentDetails,
+ order: Order,
+ bill_to: Option<BillTo>,
processing_options: Option<ProcessingOptions>,
#[serde(skip_serializing_if = "Option::is_none")]
subsequent_auth_information: Option<SubsequentAuthInformation>,
@@ -243,6 +252,24 @@ pub struct ProcessingOptions {
is_subsequent_auth: bool,
}
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct BillTo {
+ first_name: Option<Secret<String>>,
+ last_name: Option<Secret<String>>,
+ address: Option<Secret<String>>,
+ city: Option<String>,
+ state: Option<Secret<String>>,
+ zip: Option<Secret<String>>,
+ country: Option<api_enums::CountryAlpha2>,
+}
+
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct Order {
+ description: String,
+}
+
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SubsequentAuthInformation {
@@ -341,12 +368,27 @@ impl TryFrom<&AuthorizedotnetRouterData<&types::PaymentsAuthorizeRouterData>>
}),
None => None,
};
-
+ let bill_to = item
+ .router_data
+ .get_billing_address_details_as_optional()
+ .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::from(item.router_data.request.capture_method),
amount: item.amount,
- payment: payment_details,
currency_code: item.router_data.request.currency.to_string(),
+ payment: payment_details,
+ order: Order {
+ description: item.router_data.connector_request_reference_id.clone(),
+ },
+ bill_to,
processing_options,
subsequent_auth_information,
authorization_indicator_type,
|
2024-03-06T11:08:36Z
|
## 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 -->
- If the billing address is included in the payments request, it will be transmitted to the connector.
- Additionally, the `connector_request_reference_id` is now transmitted within the order description, making it visible in the transaction details on the connector dashboard.
### 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/3980
## 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)?
-->
Test payments (manual and automatic) for authorizedotnet.
1. Automatic:
- Request:
```curl
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: API_KEY_HERE' \
--data '{
"amount": 1234,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"customer_id": "StripeCustomer",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "5424000000000015",
"card_exp_month": "02",
"card_exp_year": "35",
"card_holder_name": "John Doe",
"card_cvc": "123"
}
},
"billing": {
"address": {
"first_name": "John",
"last_name": "Doe",
"line1": "Harrison Street",
"city": "San Francisco",
"state": "California",
"zip": "94016",
"country": "US"
}
},
"setup_future_usage": "on_session"
}'
```
- Response:
```json
{
"payment_id": "pay_cuLkCdbQQzkHymq2TKDU",
"merchant_id": "merchant_1709720492",
"status": "succeeded",
"amount": 1234,
"net_amount": 1234,
"amount_capturable": 0,
"amount_received": 1234,
"connector": "authorizedotnet",
"client_secret": "pay_cuLkCdbQQzkHymq2TKDU_secret_F8avCQMZYy6Ayy6KUeQd",
"created": "2024-03-06T11:14:34.973Z",
"currency": "USD",
"customer_id": "StripeCustomer",
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": "on_session",
"off_session": null,
"capture_on": null,
"capture_method": "automatic",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "0015",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "542400",
"card_extended_bin": "54240000",
"card_exp_month": "02",
"card_exp_year": "35",
"card_holder_name": "John Doe"
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": {
"address": {
"city": "San Francisco",
"country": "US",
"line1": "Harrison Street",
"line2": null,
"line3": null,
"zip": "94016",
"state": "California",
"first_name": "John",
"last_name": "Doe"
},
"phone": {
"number": null,
"country_code": null
},
"email": 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": "StripeCustomer",
"created_at": 1709723674,
"expires": 1709727274,
"secret": "epk_6a7570ed25eb463d91972aa3c5a6cca6"
},
"manual_retry_allowed": false,
"connector_transaction_id": "80015569706",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "80015569706",
"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,
"request_external_3ds_authentication": null,
"expires_on": "2024-03-06T11:29:34.973Z",
"fingerprint": null
}
```
2. Manual:
- Authorize request:
```curl
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: API_KEY_HERE' \
--data '{
"amount": 1234,
"currency": "USD",
"confirm": true,
"capture_method": "manual",
"customer_id": "StripeCustomer",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "5424000000000015",
"card_exp_month": "02",
"card_exp_year": "35",
"card_holder_name": "John Doe",
"card_cvc": "123"
}
},
"billing": {
"address": {
"first_name": "John",
"last_name": "Doe",
"line1": "Harrison Street",
"city": "San Francisco",
"state": "California",
"zip": "94016",
"country": "US"
}
},
"setup_future_usage": "on_session"
}'
```
- Authorize Response:
```json
{
"payment_id": "pay_GCVt2jy4rwpznGCPVpvs",
"merchant_id": "merchant_1709720492",
"status": "requires_capture",
"amount": 1234,
"net_amount": 1234,
"amount_capturable": 1234,
"amount_received": null,
"connector": "authorizedotnet",
"client_secret": "pay_GCVt2jy4rwpznGCPVpvs_secret_go6S99MiGAsLgJYaG7xB",
"created": "2024-03-06T11:16:02.569Z",
"currency": "USD",
"customer_id": "StripeCustomer",
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": "on_session",
"off_session": null,
"capture_on": null,
"capture_method": "manual",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "0015",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "542400",
"card_extended_bin": "54240000",
"card_exp_month": "02",
"card_exp_year": "35",
"card_holder_name": "John Doe"
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": {
"address": {
"city": "San Francisco",
"country": "US",
"line1": "Harrison Street",
"line2": null,
"line3": null,
"zip": "94016",
"state": "California",
"first_name": "John",
"last_name": "Doe"
},
"phone": {
"number": null,
"country_code": null
},
"email": 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": "StripeCustomer",
"created_at": 1709723762,
"expires": 1709727362,
"secret": "epk_cc979868f4114736aa643b628b57c171"
},
"manual_retry_allowed": false,
"connector_transaction_id": "80015569729",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "80015569729",
"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,
"request_external_3ds_authentication": null,
"expires_on": "2024-03-06T11:31:02.569Z",
"fingerprint": null
}
```
- Capture Request:
```curl
curl --location 'http://localhost:8080/payments/pay_GCVt2jy4rwpznGCPVpvs/capture' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: API_KEY_HERE' \
--data '{}'
```
- Capture Response:
```json
{
"payment_id": "pay_GCVt2jy4rwpznGCPVpvs",
"merchant_id": "merchant_1709720492",
"status": "succeeded",
"amount": 1234,
"net_amount": 1234,
"amount_capturable": 0,
"amount_received": 1234,
"connector": "authorizedotnet",
"client_secret": "pay_GCVt2jy4rwpznGCPVpvs_secret_go6S99MiGAsLgJYaG7xB",
"created": "2024-03-06T11:16:02.569Z",
"currency": "USD",
"customer_id": "StripeCustomer",
"description": null,
"refunds": null,
"disputes": null,
"mandate_id": null,
"mandate_data": null,
"setup_future_usage": "on_session",
"off_session": null,
"capture_on": null,
"capture_method": "manual",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "0015",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "542400",
"card_extended_bin": "54240000",
"card_exp_month": "02",
"card_exp_year": "35",
"card_holder_name": "John Doe"
},
"billing": null
},
"payment_token": null,
"shipping": null,
"billing": {
"address": {
"city": "San Francisco",
"country": "US",
"line1": "Harrison Street",
"line2": null,
"line3": null,
"zip": "94016",
"state": "California",
"first_name": "John",
"last_name": "Doe"
},
"phone": {
"number": null,
"country_code": null
},
"email": 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": "80015569729",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "80015569729",
"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,
"request_external_3ds_authentication": null,
"expires_on": "2024-03-06T11:31:02.569Z",
"fingerprint": null
}
```
For all the mentioned scenarios, both the billing address and the connector_request_reference_id should be visible on the Authorized.net dashboard.
<img width="596" alt="Screenshot 2024-03-06 at 4 14 57 PM" src="https://github.com/juspay/hyperswitch/assets/41580413/9a70dbea-98d8-4695-9b28-00c4e20a9c3b">
NOTE: In all the mentioned scenarios, attempt submitting partial billing addresses, and at times, no billing address at all, ensuring that all payment transactions still function correctly.
## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
a1fd36a1abea4d400386a00ccf182dfe9da5bcda
|
|
juspay/hyperswitch
|
juspay__hyperswitch-3979
|
Bug: Setup-future-usage to be defaulted to on-session
|
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 76893659e03..2bcd317bafc 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -3865,7 +3865,10 @@ pub fn validate_mandate_data_and_future_usage(
setup_future_usages: Option<api_enums::FutureUsage>,
mandate_details_present: bool,
) -> Result<(), errors::ApiErrorResponse> {
- if Some(api_enums::FutureUsage::OnSession) == setup_future_usages && mandate_details_present {
+ if mandate_details_present
+ && (Some(api_enums::FutureUsage::OnSession) == setup_future_usages
+ || setup_future_usages.is_none())
+ {
Err(errors::ApiErrorResponse::PreconditionFailed {
message: "`setup_future_usage` must be `off_session` for mandates".into(),
})
diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs
index 3a7ab7d9abe..c085382232b 100644
--- a/crates/router/src/core/payments/tokenization.rs
+++ b/crates/router/src/core/payments/tokenization.rs
@@ -102,9 +102,7 @@ where
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to serialize customer acceptance to value")?;
- let pm_id = if resp.request.get_setup_future_usage().is_some()
- && customer_acceptance.is_some()
- {
+ let pm_id = if customer_acceptance.is_some() {
let customer = maybe_customer.to_owned().get_required_value("customer")?;
let payment_method_create_request = helpers::get_payment_method_create_request(
Some(&resp.request.get_payment_method_data()),
|
2024-03-06T14:13:15Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
accept customer_acceptance to save the card
### 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 an MA and an MCA
- Do a save card payment only by passing customer_acceptance
-> Create
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_lb8obpTBmS60ZtaXLd4xVGkE69qnZKdEDfCyzM6UDJKVHyg5tEu6WkKHdukYug1F' \
--data-raw ' {"amount": 7000,
"currency": "USD",
"confirm": false,
"capture_method": "automatic",
"authentication_type": "no_three_ds",
"customer_id": "77cc",
"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
}
},
"business_country": "US",
"business_label": "default",
"payment_method": "card",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "12",
"card_exp_year": "2040",
"card_holder_name": "AKA",
"card_cvc": "123",
"nick_name": "HELO"
}
}
}'
```
-> Confirm
```
curl --location 'http://localhost:8080/payments/pay_ir21sZA1B2FN8Vn1zYT8/confirm' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_lb8obpTBmS60ZtaXLd4xVGkE69qnZKdEDfCyzM6UDJKVHyg5tEu6WkKHdukYug1F' \
--data '{
"confirm": true,
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "in sit",
"user_agent": "amet irure esse"
}}
}'
```
- the card will be saved , irrespective of the setup_future_usage
<img width="2170" alt="Screenshot 2024-03-07 at 5 19 41 PM" src="https://github.com/juspay/hyperswitch/assets/55580080/7907b2a1-2442-4986-b01f-9040dee2be1f">
## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
9bee5ab3f10d7d7c832c2ba5c4990bd85af32928
|
|
juspay/hyperswitch
|
juspay__hyperswitch-3972
|
Bug: [FIX] add doc for merchant KV flip
|
diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs
index dc38181a683..cb41c8eb05c 100644
--- a/crates/openapi/src/openapi.rs
+++ b/crates/openapi/src/openapi.rs
@@ -90,6 +90,7 @@ Never share your secret api keys. Keep them guarded and secure.
routes::merchant_account::retrieve_merchant_account,
routes::merchant_account::update_merchant_account,
routes::merchant_account::delete_merchant_account,
+ routes::merchant_account::merchant_account_kv_status,
// Routes for merchant connector account
routes::merchant_connector_account::payment_connector_create,
@@ -413,6 +414,8 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::admin::MerchantAccountResponse,
api_models::admin::MerchantConnectorId,
api_models::admin::MerchantDetails,
+ api_models::admin::ToggleKVRequest,
+ api_models::admin::ToggleKVResponse,
api_models::admin::WebhookDetails,
api_models::api_keys::ApiKeyExpiration,
api_models::api_keys::CreateApiKeyRequest,
diff --git a/crates/openapi/src/routes/merchant_account.rs b/crates/openapi/src/routes/merchant_account.rs
index 967e28225c2..6301844bf3c 100644
--- a/crates/openapi/src/routes/merchant_account.rs
+++ b/crates/openapi/src/routes/merchant_account.rs
@@ -123,3 +123,35 @@ pub async fn update_merchant_account() {}
security(("admin_api_key" = []))
)]
pub async fn delete_merchant_account() {}
+
+/// Merchant Account - KV Status
+///
+/// Toggle KV mode for the Merchant Account
+#[utoipa::path(
+ post,
+ path = "/accounts/{account_id}/kv",
+ request_body (
+ content = ToggleKVRequest,
+ examples (
+ ("Enable KV for Merchant" = (
+ value = json!({
+ "kv_enabled": "true"
+ })
+ )),
+ ("Disable KV for Merchant" = (
+ value = json!({
+ "kv_enabled": "false"
+ })
+ )))
+ ),
+ params (("account_id" = String, Path, description = "The unique identifier for the merchant account")),
+ responses(
+ (status = 200, description = "KV mode is enabled/disabled for Merchant Account", body = ToggleKVResponse),
+ (status = 400, description = "Invalid data"),
+ (status = 404, description = "Merchant account not found")
+ ),
+ tag = "Merchant Account",
+ operation_id = "Enable/Disable KV for a Merchant Account",
+ security(("admin_api_key" = []))
+)]
+pub async fn merchant_account_kv_status() {}
diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json
index 9e64f3e9d03..dfc95f9235c 100644
--- a/openapi/openapi_spec.json
+++ b/openapi/openapi_spec.json
@@ -913,6 +913,72 @@
]
}
},
+ "/accounts/{account_id}/kv": {
+ "post": {
+ "tags": [
+ "Merchant Account"
+ ],
+ "summary": "Merchant Account - KV Status",
+ "description": "Merchant Account - KV Status\n\nToggle KV mode for the Merchant Account",
+ "operationId": "Enable/Disable KV for a Merchant Account",
+ "parameters": [
+ {
+ "name": "account_id",
+ "in": "path",
+ "description": "The unique identifier for the merchant account",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ToggleKVRequest"
+ },
+ "examples": {
+ "Disable KV for Merchant": {
+ "value": {
+ "kv_enabled": "false"
+ }
+ },
+ "Enable KV for Merchant": {
+ "value": {
+ "kv_enabled": "true"
+ }
+ }
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "KV mode is enabled/disabled for Merchant Account",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ToggleKVResponse"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Invalid data"
+ },
+ "404": {
+ "description": "Merchant account not found"
+ }
+ },
+ "security": [
+ {
+ "admin_api_key": []
+ }
+ ]
+ }
+ },
"/api_keys/{merchant_id)": {
"post": {
"tags": [
@@ -16228,6 +16294,39 @@
}
}
},
+ "ToggleKVRequest": {
+ "type": "object",
+ "required": [
+ "kv_enabled"
+ ],
+ "properties": {
+ "kv_enabled": {
+ "type": "boolean",
+ "description": "Status of KV for the specific merchant",
+ "example": true
+ }
+ }
+ },
+ "ToggleKVResponse": {
+ "type": "object",
+ "required": [
+ "merchant_id",
+ "kv_enabled"
+ ],
+ "properties": {
+ "merchant_id": {
+ "type": "string",
+ "description": "The identifier for the Merchant Account",
+ "example": "y3oqhf46pyzuxjbcn2giaqnb44",
+ "maxLength": 255
+ },
+ "kv_enabled": {
+ "type": "boolean",
+ "description": "Status of KV for the specific merchant",
+ "example": true
+ }
+ }
+ },
"TouchNGoRedirection": {
"type": "object"
},
|
2024-02-22T11:57:57Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Enhancement
## Description
<!-- Describe your changes in detail -->
Added API reference for enabling/disabling KV for a merchant
## 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).
-->
Added doc for KV toggle APi
## 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
## 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
|
bbb3d3d1e26f303964a495606dece7958f6c40fc
|
|
juspay/hyperswitch
|
juspay__hyperswitch-3960
|
Bug: [FEATURE] Add USD Currency Filter for Bank Of America
### Feature Description
The Bankofamerica connector needs to have a currency filter, restricting support exclusively to USD payments.
### Possible Implementation
Config 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/config/config.example.toml b/config/config.example.toml
index dd05eb61d47..e9e80911e84 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -454,6 +454,12 @@ pix = { country = "BR", currency = "BRL" }
red_compra = { country = "CL", currency = "CLP" }
red_pagos = { country = "UY", currency = "UYU" }
+[pm_filters.bankofamerica]
+credit = { currency = "USD" }
+debit = { currency = "USD" }
+apple_pay = { currency = "USD" }
+google_pay = { currency = "USD" }
+
[pm_filters.stax]
credit = { currency = "USD" }
debit = { currency = "USD" }
diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml
index b7585f0c2ef..3ed64840b78 100644
--- a/config/deployments/integration_test.toml
+++ b/config/deployments/integration_test.toml
@@ -212,6 +212,12 @@ we_chat_pay = { country = "AU,NZ,CN,JP,HK,SG,ES,GB,SE,NO,AT,NL,DE,CY,CH,BE,FR,DK
google_pay.currency = "CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD,AUD,NZD,CAD"
paypal.currency = "CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD,AUD,NZD,CAD"
+[pm_filters.bankofamerica]
+credit = { currency = "USD" }
+debit = { currency = "USD" }
+apple_pay = { currency = "USD" }
+google_pay = { currency = "USD" }
+
[pm_filters.braintree]
paypal.currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,RUB,SGD,SEK,CHF,THB,USD"
diff --git a/config/deployments/production.toml b/config/deployments/production.toml
index a105c4c0e94..382ad018f1d 100644
--- a/config/deployments/production.toml
+++ b/config/deployments/production.toml
@@ -226,6 +226,12 @@ we_chat_pay = { country = "AU,NZ,CN,JP,HK,SG,ES,GB,SE,NO,AT,NL,DE,CY,CH,BE,FR,DK
google_pay.currency = "CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD,AUD,NZD,CAD"
paypal.currency = "CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD,AUD,NZD,CAD"
+[pm_filters.bankofamerica]
+credit = { currency = "USD" }
+debit = { currency = "USD" }
+apple_pay = { currency = "USD" }
+google_pay = { currency = "USD" }
+
[pm_filters.braintree]
paypal.currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,RUB,SGD,SEK,CHF,THB,USD"
diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml
index ed718caa30d..396fd8b8628 100644
--- a/config/deployments/sandbox.toml
+++ b/config/deployments/sandbox.toml
@@ -227,6 +227,12 @@ pix = { country = "BR", currency = "BRL" }
google_pay.currency = "CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD,AUD,NZD,CAD"
paypal.currency = "CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD,AUD,NZD,CAD"
+[pm_filters.bankofamerica]
+credit = { currency = "USD" }
+debit = { currency = "USD" }
+apple_pay = { currency = "USD" }
+google_pay = { currency = "USD" }
+
[pm_filters.braintree]
paypal.currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,RUB,SGD,SEK,CHF,THB,USD"
diff --git a/config/development.toml b/config/development.toml
index 5d7366a89f3..c7bfefc3435 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -365,6 +365,12 @@ pay_easy = {country = "JP", currency = "JPY"}
pix = { country = "BR", currency = "BRL" }
boleto = { country = "BR", currency = "BRL" }
+[pm_filters.bankofamerica]
+credit = { currency = "USD" }
+debit = { currency = "USD" }
+apple_pay = { currency = "USD" }
+google_pay = { currency = "USD" }
+
[pm_filters.braintree]
paypal = { currency = "AUD,BRL,CAD,CNY,CZK,DKK,EUR,HKD,HUF,ILS,JPY,MYR,MXN,TWD,NZD,NOK,PHP,PLN,GBP,RUB,SGD,SEK,CHF,THB,USD" }
credit = { not_available_flows = { capture_method = "manual" } }
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index f6de5ada7fa..892086a7b9f 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -333,6 +333,12 @@ cashapp = {country = "US", currency = "USD"}
[pm_filters.prophetpay]
card_redirect = { currency = "USD" }
+[pm_filters.bankofamerica]
+credit = { currency = "USD" }
+debit = { currency = "USD" }
+apple_pay = { currency = "USD" }
+google_pay = { currency = "USD" }
+
[pm_filters.helcim]
credit = { currency = "USD" }
debit = { currency = "USD" }
|
2024-03-05T10:20:49Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [x] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
The Bankofamerica connector now includes a currency filter, restricting support exclusively to USD payments.
### Additional Changes
- [ ] This PR modifies the API contract
- [ ] This PR modifies the database schema
- [x] This PR modifies application configuration/environment variables
Following are the paths where you can find config files:
1. `config/development.toml`
2. `config/deployments/integration_test.toml`
3. `config/deployments/sandbox.toml`
4. `config/deployments/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/3960
## 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 Method List needs to be verified for USD and Non-USD payments via BOA:
1. Payments Request(with confirm false):
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: API_KEY_HERE' \
--data-raw '{
"amount": 1404,
"currency": "INR",
"confirm": false,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"customer_id": "CustomerX",
"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": "eqnkl",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "תל אביב",
"state": "California",
"zip": "46282",
"country": "US",
"first_name": "joseph",
"last_name": "ewcjwd"
},
"phone": {
"number": "8056594427",
"country_code": "+97"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"business_label": "food",
"business_country": "US"
}'
```
Payments Response:
```
{
"payment_id": "pay_3ftTdmvei4RVQamsfyfJ",
"merchant_id": "merchant_1706697715",
"status": "requires_payment_method",
"amount": 1404,
"net_amount": 1404,
"amount_capturable": 0,
"amount_received": null,
"connector": null,
"client_secret": "pay_3ftTdmvei4RVQamsfyfJ_secret_SM3IbzER2kXk3jmHe1s2",
"created": "2024-03-13T07:26:39.814Z",
"currency": "INR",
"customer_id": "CustomerX",
"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": null,
"billing": {
"address": {
"city": "תל אביב",
"country": "US",
"line1": "eqnkl",
"line2": "Harrison Street",
"line3": "Harrison Street",
"zip": "46282",
"state": "California",
"first_name": "joseph",
"last_name": "ewcjwd"
},
"phone": {
"number": "8056594427",
"country_code": "+97"
},
"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": "US",
"business_label": "food",
"business_sub_label": null,
"allowed_payment_method_types": null,
"ephemeral_key": {
"customer_id": "CustomerX",
"created_at": 1710314799,
"expires": 1710318399,
"secret": "epk_35a516b093434ef6a7bff36ae0efd437"
},
"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_j9PVFpZYzQU1j7yyjkJJ",
"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-03-13T07:41:39.813Z",
"fingerprint": null,
"payment_method_id": null,
"payment_method_status": null
}
```
2. Payment Methods List Request:
```
`curl --location 'http://localhost:8080/account/payment_methods?client_secret=CLIENT_SECRET_HERE' \
--header 'Accept: application/json' \
--header 'api-key: API_KEY_HERE'`
```
Payment Methods List Response:
- For Non-USD Currencies:
```
{
"redirect_url": "https://google.com/success",
"currency": "INR",
"payment_methods": [],
"mandate_payment": null,
"merchant_name": "NewAge Retailer",
"show_surcharge_breakup_screen": false,
"payment_type": "normal"
}
```
- For USD:
```
{
"redirect_url": "https://google.com/success",
"currency": "USD",
"payment_methods": [
{
"payment_method": "wallet",
"payment_method_types": [
{
"payment_method_type": "google_pay",
"payment_experience": [
{
"payment_experience_type": "redirect_to_url",
"eligible_connectors": [
"bankofamerica"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"billing.address.last_name": {
"required_field": "billing.address.last_name",
"display_name": "billing_last_name",
"field_type": "user_billing_name",
"value": "ewcjwd"
},
"billing.address.country": {
"required_field": "billing.address.country",
"display_name": "country",
"field_type": {
"user_address_country": {
"options": [
"ALL"
]
}
},
"value": "US"
},
"billing.address.city": {
"required_field": "billing.address.city",
"display_name": "city",
"field_type": "user_address_city",
"value": "תל אביב"
},
"email": {
"required_field": "email",
"display_name": "email",
"field_type": "user_email_address",
"value": "guest@example.com"
},
"billing.address.line1": {
"required_field": "billing.address.line1",
"display_name": "line1",
"field_type": "user_address_line1",
"value": "eqnkl"
},
"billing.address.first_name": {
"required_field": "billing.address.first_name",
"display_name": "billing_first_name",
"field_type": "user_billing_name",
"value": "joseph"
},
"billing.address.zip": {
"required_field": "billing.address.zip",
"display_name": "zip",
"field_type": "user_address_pincode",
"value": "46282"
},
"billing.address.state": {
"required_field": "billing.address.state",
"display_name": "state",
"field_type": "user_address_state",
"value": "California"
}
},
"surcharge_details": null,
"pm_auth_connector": null
},
{
"payment_method_type": "apple_pay",
"payment_experience": [
{
"payment_experience_type": "invoke_sdk_client",
"eligible_connectors": [
"bankofamerica"
]
}
],
"card_networks": null,
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"billing.address.country": {
"required_field": "billing.address.country",
"display_name": "country",
"field_type": {
"user_address_country": {
"options": [
"ALL"
]
}
},
"value": "US"
},
"billing.address.first_name": {
"required_field": "billing.address.first_name",
"display_name": "billing_first_name",
"field_type": "user_billing_name",
"value": "joseph"
},
"billing.address.state": {
"required_field": "billing.address.state",
"display_name": "state",
"field_type": "user_address_state",
"value": "California"
},
"billing.address.last_name": {
"required_field": "billing.address.last_name",
"display_name": "billing_last_name",
"field_type": "user_billing_name",
"value": "ewcjwd"
},
"email": {
"required_field": "email",
"display_name": "email",
"field_type": "user_email_address",
"value": "guest@example.com"
},
"billing.address.city": {
"required_field": "billing.address.city",
"display_name": "city",
"field_type": "user_address_city",
"value": "תל אביב"
},
"billing.address.line1": {
"required_field": "billing.address.line1",
"display_name": "line1",
"field_type": "user_address_line1",
"value": "eqnkl"
},
"billing.address.zip": {
"required_field": "billing.address.zip",
"display_name": "zip",
"field_type": "user_address_pincode",
"value": "46282"
}
},
"surcharge_details": null,
"pm_auth_connector": null
}
]
},
{
"payment_method": "card",
"payment_method_types": [
{
"payment_method_type": "debit",
"payment_experience": null,
"card_networks": [
{
"card_network": "Discover",
"surcharge_details": null,
"eligible_connectors": [
"bankofamerica"
]
},
{
"card_network": "Mastercard",
"surcharge_details": null,
"eligible_connectors": [
"bankofamerica"
]
},
{
"card_network": "Visa",
"surcharge_details": null,
"eligible_connectors": [
"bankofamerica"
]
},
{
"card_network": "JCB",
"surcharge_details": null,
"eligible_connectors": [
"bankofamerica"
]
}
],
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"billing.address.line1": {
"required_field": "billing.address.line1",
"display_name": "line1",
"field_type": "user_address_line1",
"value": "eqnkl"
},
"billing.address.country": {
"required_field": "billing.address.country",
"display_name": "country",
"field_type": {
"user_address_country": {
"options": [
"ALL"
]
}
},
"value": "US"
},
"payment_method_data.card.card_exp_month": {
"required_field": "payment_method_data.card.card_exp_month",
"display_name": "card_exp_month",
"field_type": "user_card_expiry_month",
"value": null
},
"billing.address.state": {
"required_field": "billing.address.state",
"display_name": "state",
"field_type": "user_address_state",
"value": "California"
},
"billing.address.zip": {
"required_field": "billing.address.zip",
"display_name": "zip",
"field_type": "user_address_pincode",
"value": "46282"
},
"payment_method_data.card.card_cvc": {
"required_field": "payment_method_data.card.card_cvc",
"display_name": "card_cvc",
"field_type": "user_card_cvc",
"value": null
},
"billing.address.first_name": {
"required_field": "billing.address.first_name",
"display_name": "billing_first_name",
"field_type": "user_billing_name",
"value": "joseph"
},
"payment_method_data.card.card_exp_year": {
"required_field": "payment_method_data.card.card_exp_year",
"display_name": "card_exp_year",
"field_type": "user_card_expiry_year",
"value": null
},
"email": {
"required_field": "email",
"display_name": "email",
"field_type": "user_email_address",
"value": "guest@example.com"
},
"billing.address.city": {
"required_field": "billing.address.city",
"display_name": "city",
"field_type": "user_address_city",
"value": "תל אביב"
},
"payment_method_data.card.card_number": {
"required_field": "payment_method_data.card.card_number",
"display_name": "card_number",
"field_type": "user_card_number",
"value": null
},
"billing.address.last_name": {
"required_field": "billing.address.last_name",
"display_name": "billing_last_name",
"field_type": "user_billing_name",
"value": "ewcjwd"
}
},
"surcharge_details": null,
"pm_auth_connector": null
},
{
"payment_method_type": "credit",
"payment_experience": null,
"card_networks": [
{
"card_network": "Visa",
"surcharge_details": null,
"eligible_connectors": [
"bankofamerica"
]
},
{
"card_network": "Mastercard",
"surcharge_details": null,
"eligible_connectors": [
"bankofamerica"
]
},
{
"card_network": "JCB",
"surcharge_details": null,
"eligible_connectors": [
"bankofamerica"
]
},
{
"card_network": "Discover",
"surcharge_details": null,
"eligible_connectors": [
"bankofamerica"
]
}
],
"bank_names": null,
"bank_debits": null,
"bank_transfers": null,
"required_fields": {
"payment_method_data.card.card_cvc": {
"required_field": "payment_method_data.card.card_cvc",
"display_name": "card_cvc",
"field_type": "user_card_cvc",
"value": null
},
"billing.address.state": {
"required_field": "billing.address.state",
"display_name": "state",
"field_type": "user_address_state",
"value": "California"
},
"billing.address.country": {
"required_field": "billing.address.country",
"display_name": "country",
"field_type": {
"user_address_country": {
"options": [
"ALL"
]
}
},
"value": "US"
},
"payment_method_data.card.card_number": {
"required_field": "payment_method_data.card.card_number",
"display_name": "card_number",
"field_type": "user_card_number",
"value": null
},
"billing.address.city": {
"required_field": "billing.address.city",
"display_name": "city",
"field_type": "user_address_city",
"value": "תל אביב"
},
"payment_method_data.card.card_exp_month": {
"required_field": "payment_method_data.card.card_exp_month",
"display_name": "card_exp_month",
"field_type": "user_card_expiry_month",
"value": null
},
"billing.address.last_name": {
"required_field": "billing.address.last_name",
"display_name": "billing_last_name",
"field_type": "user_billing_name",
"value": "ewcjwd"
},
"payment_method_data.card.card_exp_year": {
"required_field": "payment_method_data.card.card_exp_year",
"display_name": "card_exp_year",
"field_type": "user_card_expiry_year",
"value": null
},
"billing.address.zip": {
"required_field": "billing.address.zip",
"display_name": "zip",
"field_type": "user_address_pincode",
"value": "46282"
},
"billing.address.line1": {
"required_field": "billing.address.line1",
"display_name": "line1",
"field_type": "user_address_line1",
"value": "eqnkl"
},
"billing.address.first_name": {
"required_field": "billing.address.first_name",
"display_name": "billing_first_name",
"field_type": "user_billing_name",
"value": "joseph"
},
"email": {
"required_field": "email",
"display_name": "email",
"field_type": "user_email_address",
"value": "guest@example.com"
}
},
"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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
c65729adc9009f046398312a16841532fdc177da
|
|
juspay/hyperswitch
|
juspay__hyperswitch-3977
|
Bug: [BUG]: [Adyen] Webhook Psync response Handler
### Bug Description
Currently the Psync response handler for webhook tightly coupled to payments response which is creating a lot of bugs in status and transaction id updates
- Update Psync response handler to consume the incoming webhook response
- Handle Webhook Status Mapping
### Expected Behavior
Decouple the Webhook Response from Payments response and handle all the status and reference ids separately
### Actual Behavior
Currently the Psync response handler for webhook tightly coupled to payments response which is creating a lot of bugs in status and transaction id updates
- Update Psync response handler to consume the incoming webhook response
- Handle Webhook Status Mapping
### 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/adyen.rs b/crates/router/src/connector/adyen.rs
index 93301364e62..67e319ddc22 100644
--- a/crates/router/src/connector/adyen.rs
+++ b/crates/router/src/connector/adyen.rs
@@ -403,6 +403,13 @@ impl
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
+ fn get_5xx_error_response(
+ &self,
+ res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
}
impl api::PaymentSession for Adyen {}
@@ -516,6 +523,13 @@ impl
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
+ fn get_5xx_error_response(
+ &self,
+ res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
}
/// Payment Sync can be useful only incase of Redirect flow.
@@ -681,6 +695,13 @@ impl
) -> CustomResult<services::CaptureSyncMethod, errors::ConnectorError> {
Ok(services::CaptureSyncMethod::Individual)
}
+ fn get_5xx_error_response(
+ &self,
+ res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
}
impl
@@ -795,6 +816,14 @@ impl
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
+
+ fn get_5xx_error_response(
+ &self,
+ res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
}
impl api::PaymentsPreProcessing for Adyen {}
@@ -925,6 +954,14 @@ impl
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
+
+ fn get_5xx_error_response(
+ &self,
+ res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
}
impl
@@ -1022,6 +1059,13 @@ impl
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
+ fn get_5xx_error_response(
+ &self,
+ res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
}
impl api::Payouts for Adyen {}
@@ -1129,6 +1173,13 @@ impl services::ConnectorIntegration<api::PoCancel, types::PayoutsData, types::Pa
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
+ fn get_5xx_error_response(
+ &self,
+ res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
}
#[cfg(feature = "payouts")]
@@ -1227,6 +1278,13 @@ impl services::ConnectorIntegration<api::PoCreate, types::PayoutsData, types::Pa
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
+ fn get_5xx_error_response(
+ &self,
+ res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
}
#[cfg(feature = "payouts")]
@@ -1330,6 +1388,13 @@ impl
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
+ fn get_5xx_error_response(
+ &self,
+ res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
}
#[cfg(feature = "payouts")]
@@ -1446,6 +1511,13 @@ impl services::ConnectorIntegration<api::PoFulfill, types::PayoutsData, types::P
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
+ fn get_5xx_error_response(
+ &self,
+ res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
}
impl api::Refund for Adyen {}
@@ -1553,6 +1625,13 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref
) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
+ fn get_5xx_error_response(
+ &self,
+ res: types::Response,
+ event_builder: Option<&mut ConnectorEvent>,
+ ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res, event_builder)
+ }
}
impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData>
@@ -1717,7 +1796,7 @@ impl api::IncomingWebhook for Adyen {
let notif = get_webhook_object_from_body(request.body)
.change_context(errors::ConnectorError::WebhookEventTypeNotFound)?;
- let response: adyen::Response = notif.into();
+ let response = adyen::AdyenWebhookResponse::from(notif);
Ok(Box::new(response))
}
diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs
index 9fbf7d99812..c44d590e2f1 100644
--- a/crates/router/src/connector/adyen/transformers.rs
+++ b/crates/router/src/connector/adyen/transformers.rs
@@ -3,7 +3,7 @@ use api_models::payouts::PayoutMethodData;
use api_models::{enums, payments, webhooks};
use cards::CardNumber;
use common_utils::{ext_traits::Encode, pii};
-use error_stack::ResultExt;
+use error_stack::{IntoReport, ResultExt};
use masking::{ExposeInterface, PeekInterface};
use reqwest::Url;
use serde::{Deserialize, Serialize};
@@ -24,7 +24,7 @@ use crate::{
self,
api::{self, enums as api_enums},
storage::enums as storage_enums,
- transformers::ForeignFrom,
+ transformers::{ForeignFrom, ForeignTryFrom},
PaymentsAuthorizeData,
},
utils as crate_utils,
@@ -271,6 +271,31 @@ impl ForeignFrom<(bool, AdyenStatus, Option<common_enums::PaymentMethodType>)>
}
}
+impl ForeignTryFrom<(bool, AdyenWebhookStatus)> for storage_enums::AttemptStatus {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn foreign_try_from(
+ (is_manual_capture, adyen_webhook_status): (bool, AdyenWebhookStatus),
+ ) -> Result<Self, Self::Error> {
+ match adyen_webhook_status {
+ AdyenWebhookStatus::Authorised => match is_manual_capture {
+ true => Ok(Self::Authorized),
+ // In case of Automatic capture Authorized is the final status of the payment
+ false => Ok(Self::Charged),
+ },
+ AdyenWebhookStatus::AuthorisationFailed => Ok(Self::Failure),
+ AdyenWebhookStatus::Cancelled => Ok(Self::Voided),
+ AdyenWebhookStatus::CancelFailed => Ok(Self::VoidFailed),
+ AdyenWebhookStatus::Captured => Ok(Self::Charged),
+ AdyenWebhookStatus::CaptureFailed => Ok(Self::CaptureFailed),
+ //If Unexpected Event is received, need to understand how it reached this point
+ //Webhooks with Payment Events only should try to conume this resource object.
+ AdyenWebhookStatus::UnexpectedEvent => {
+ Err(errors::ConnectorError::WebhookBodyDecodingFailed).into_report()
+ }
+ }
+ }
+}
+
#[derive(Debug, Serialize, Deserialize, Eq, PartialEq)]
pub struct AdyenRedirectRequest {
pub details: AdyenRedirectRequestTypes,
@@ -320,6 +345,7 @@ pub enum AdyenPaymentResponse {
QrCodeResponse(Box<QrCodeResponseResponse>),
RedirectionResponse(Box<RedirectionResponse>),
RedirectionErrorResponse(Box<RedirectionErrorResponse>),
+ WebhookResponse(Box<AdyenWebhookResponse>),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -332,8 +358,31 @@ pub struct Response {
refusal_reason: Option<String>,
refusal_reason_code: Option<String>,
additional_data: Option<AdditionalData>,
- // event_code will be available only in webhook body
- event_code: Option<WebhookEventCode>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub enum AdyenWebhookStatus {
+ Authorised,
+ AuthorisationFailed,
+ Cancelled,
+ CancelFailed,
+ Captured,
+ CaptureFailed,
+ UnexpectedEvent,
+}
+
+//Creating custom struct which can be consumed in Psync Handler triggered from Webhooks
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct AdyenWebhookResponse {
+ transaction_id: String,
+ payment_reference: Option<String>,
+ status: AdyenWebhookStatus,
+ amount: Option<Amount>,
+ merchant_reference_id: String,
+ refusal_reason: Option<String>,
+ refusal_reason_code: Option<String>,
+ event_code: WebhookEventCode,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -3091,7 +3140,6 @@ pub fn get_adyen_response(
> {
let status =
storage_enums::AttemptStatus::foreign_from((is_capture_manual, response.result_code, pmt));
- let status = update_attempt_status_based_on_event_type_if_needed(status, &response.event_code);
let error = if response.refusal_reason.is_some() || response.refusal_reason_code.is_some() {
Some(types::ErrorResponse {
code: response
@@ -3135,10 +3183,11 @@ pub fn get_adyen_response(
Ok((status, error, payments_response_data))
}
-pub fn get_adyen_response_for_multiple_partial_capture(
- response: Response,
+pub fn get_webhook_response(
+ response: AdyenWebhookResponse,
+ is_capture_manual: bool,
+ is_multiple_capture_psync_flow: bool,
status_code: u16,
- pmt: Option<enums::PaymentMethodType>,
) -> errors::CustomResult<
(
storage_enums::AttemptStatus,
@@ -3147,28 +3196,53 @@ pub fn get_adyen_response_for_multiple_partial_capture(
),
errors::ConnectorError,
> {
- let (status, error, _) = get_adyen_response(response.clone(), true, status_code, pmt)?;
- let status = update_attempt_status_based_on_event_type_if_needed(status, &response.event_code);
- let capture_sync_response_list = utils::construct_captures_response_hashmap(vec![response]);
- Ok((
- status,
- error,
- types::PaymentsResponseData::MultipleCaptureResponse {
- capture_sync_response_list,
- },
- ))
-}
+ let status = storage_enums::AttemptStatus::foreign_try_from((
+ is_capture_manual,
+ response.status.clone(),
+ ))?;
+ let error = if response.refusal_reason.is_some() || response.refusal_reason_code.is_some() {
+ Some(types::ErrorResponse {
+ code: response
+ .refusal_reason_code
+ .clone()
+ .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()),
+ message: response
+ .refusal_reason
+ .clone()
+ .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()),
+ reason: response.refusal_reason.clone(),
+ status_code,
+ attempt_status: None,
+ connector_transaction_id: Some(response.transaction_id.clone()),
+ })
+ } else {
+ None
+ };
-fn update_attempt_status_based_on_event_type_if_needed(
- status: storage_enums::AttemptStatus,
- event: &Option<WebhookEventCode>,
-) -> storage_enums::AttemptStatus {
- if status == storage_enums::AttemptStatus::Authorized
- && event == &Some(WebhookEventCode::Capture)
- {
- storage_enums::AttemptStatus::Charged
+ if is_multiple_capture_psync_flow {
+ let capture_sync_response_list = utils::construct_captures_response_hashmap(vec![response]);
+ Ok((
+ status,
+ error,
+ types::PaymentsResponseData::MultipleCaptureResponse {
+ capture_sync_response_list,
+ },
+ ))
} else {
- status
+ let payments_response_data = types::PaymentsResponseData::TransactionResponse {
+ resource_id: types::ResponseId::ConnectorTransactionId(
+ response
+ .payment_reference
+ .unwrap_or(response.transaction_id),
+ ),
+ redirection_data: None,
+ mandate_reference: None,
+ connector_metadata: None,
+ network_txn_id: None,
+ connector_response_reference_id: Some(response.merchant_reference_id),
+ incremental_authorization_allowed: None,
+ };
+ Ok((status, error, payments_response_data))
}
}
@@ -3656,11 +3730,7 @@ impl<F, Req>
let is_manual_capture = utils::is_manual_capture(capture_method);
let (status, error, payment_response_data) = match item.response {
AdyenPaymentResponse::Response(response) => {
- if is_multiple_capture_psync_flow {
- get_adyen_response_for_multiple_partial_capture(*response, item.http_code, pmt)?
- } else {
- get_adyen_response(*response, is_manual_capture, item.http_code, pmt)?
- }
+ get_adyen_response(*response, is_manual_capture, item.http_code, pmt)?
}
AdyenPaymentResponse::PresentToShopper(response) => {
get_present_to_shopper_response(*response, is_manual_capture, item.http_code, pmt)?
@@ -3674,6 +3744,12 @@ impl<F, Req>
AdyenPaymentResponse::RedirectionErrorResponse(response) => {
get_redirection_error_response(*response, is_manual_capture, item.http_code, pmt)?
}
+ AdyenPaymentResponse::WebhookResponse(response) => get_webhook_response(
+ *response,
+ is_manual_capture,
+ is_multiple_capture_psync_flow,
+ item.http_code,
+ )?,
};
Ok(Self {
@@ -3893,6 +3969,8 @@ pub enum WebhookEventCode {
Refund,
CancelOrRefund,
Cancellation,
+ Capture,
+ CaptureFailed,
RefundFailed,
RefundReversed,
NotificationOfChargeback,
@@ -3901,8 +3979,6 @@ pub enum WebhookEventCode {
SecondChargeback,
PrearbitrationWon,
PrearbitrationLost,
- Capture,
- CaptureFailed,
#[serde(other)]
Unknown,
}
@@ -4046,52 +4122,81 @@ pub struct AdyenIncomingWebhook {
pub notification_items: Vec<AdyenItemObjectWH>,
}
-impl From<AdyenNotificationRequestItemWH> for Response {
+impl From<AdyenNotificationRequestItemWH> for AdyenWebhookResponse {
fn from(notif: AdyenNotificationRequestItemWH) -> Self {
Self {
- psp_reference: notif.psp_reference,
- merchant_reference: notif.merchant_reference,
- result_code: match notif.success.as_str() {
- "true" => {
- if notif.event_code == WebhookEventCode::Cancellation {
- AdyenStatus::Cancelled
+ transaction_id: notif.psp_reference,
+ payment_reference: notif.original_reference,
+ //Translating into custom status so that it can be clearly mapped to out attempt_status
+ status: match notif.event_code {
+ WebhookEventCode::Authorisation => {
+ if is_success_scenario(notif.success) {
+ AdyenWebhookStatus::Authorised
} else {
- AdyenStatus::Authorised
+ AdyenWebhookStatus::AuthorisationFailed
}
}
- _ => AdyenStatus::Refused,
+ WebhookEventCode::Cancellation => {
+ if is_success_scenario(notif.success) {
+ AdyenWebhookStatus::Cancelled
+ } else {
+ AdyenWebhookStatus::CancelFailed
+ }
+ }
+ WebhookEventCode::Capture => {
+ if is_success_scenario(notif.success) {
+ AdyenWebhookStatus::Captured
+ } else {
+ AdyenWebhookStatus::CaptureFailed
+ }
+ }
+ WebhookEventCode::CaptureFailed => AdyenWebhookStatus::CaptureFailed,
+ WebhookEventCode::CancelOrRefund
+ | WebhookEventCode::Refund
+ | WebhookEventCode::RefundFailed
+ | WebhookEventCode::RefundReversed
+ | WebhookEventCode::NotificationOfChargeback
+ | WebhookEventCode::Chargeback
+ | WebhookEventCode::ChargebackReversed
+ | WebhookEventCode::SecondChargeback
+ | WebhookEventCode::PrearbitrationWon
+ | WebhookEventCode::PrearbitrationLost
+ | WebhookEventCode::Unknown => AdyenWebhookStatus::UnexpectedEvent,
},
amount: Some(Amount {
value: notif.amount.value,
currency: notif.amount.currency,
}),
+ merchant_reference_id: notif.merchant_reference,
refusal_reason: None,
refusal_reason_code: None,
- additional_data: None,
- event_code: Some(notif.event_code),
+ event_code: notif.event_code,
}
}
}
-impl utils::MultipleCaptureSyncResponse for Response {
+//This will be triggered in Psync handler of webhook response
+impl utils::MultipleCaptureSyncResponse for AdyenWebhookResponse {
fn get_connector_capture_id(&self) -> String {
- self.psp_reference.clone()
+ self.transaction_id.clone()
}
fn get_capture_attempt_status(&self) -> enums::AttemptStatus {
- match self.result_code {
- AdyenStatus::Authorised => enums::AttemptStatus::Charged,
+ match self.status {
+ AdyenWebhookStatus::Captured => enums::AttemptStatus::Charged,
_ => enums::AttemptStatus::CaptureFailed,
}
}
fn is_capture_response(&self) -> bool {
- self.event_code == Some(WebhookEventCode::Capture)
- || self.event_code == Some(WebhookEventCode::CaptureFailed)
+ matches!(
+ self.event_code,
+ WebhookEventCode::Capture | WebhookEventCode::CaptureFailed
+ )
}
fn get_connector_reference_id(&self) -> Option<String> {
- Some(self.merchant_reference.clone())
+ Some(self.merchant_reference_id.clone())
}
fn get_amount_captured(&self) -> Option<i64> {
|
2024-03-06T09:30:25Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [X] Bugfix
- [ ] New feature
- [ ] Enhancement
- [X] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
- Update Psync response handler to consume the incoming webhook response
- Handle Webhook Status Mapping
### 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).
-->
#3977
## 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 Adyen all the subsequent payments are confirmed via Webhooks, So test Capture, Cancel, Refunds and Wallets payments.
Payment Methods Need to be tested
- Klarna (Manual Capture)
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_ooWwJsn2dIWX2JrPdAbV6SYbxVBF5W0LY2ZvWHV2U3F5UXRQdHDAm9zt5q7Hk0HL' \
--data-raw '{
"amount": 6540,
"currency": "EUR",
"confirm": true,
"capture_method": "manual",
"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",
"profile_id": "pro_doSItPZQZBbfoS0iEf81",
"business_country": "US",
"payment_method": "pay_later",
"payment_method_type": "klarna",
"payment_experience": "redirect_to_url",
"connector": [
"adyen"
],
"payment_method_data": {
"pay_later": {
"klarna_redirect": {
"billing_email": "hyperswitch_sdk_demo_id@gmail.com",
"billing_country": "DE"
}
}
},
"routing": {
"type": "single",
"data": "adyen"
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "DE",
"first_name": "PiX"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "PiX"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}'
```
- Paypal (Manual Capture)
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_ooWwJsn2dIWX2JrPdAbV6SYbxVBF5W0LY2ZvWHV2U3F5UXRQdHDAm9zt5q7Hk0HL' \
--data-raw '{
"amount": 6540,
"currency": "USD",
"confirm": true,
"capture_method": "manual",
"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",
"profile_id": "pro_doSItPZQZBbfoS0iEf81",
"business_country": "US",
"payment_method": "wallet",
"payment_method_type": "paypal",
"payment_method_data": {
"wallet": {
"paypal_redirect": {}
}
},
"routing": {
"type": "single",
"data": "adyen"
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "DE",
"first_name": "PiX"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "PiX"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}'
```
- Cards (Automatic and Manual)
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_ooWwJsn2dIWX2JrPdAbV6SYbxVBF5W0LY2ZvWHV2U3F5UXRQdHDAm9zt5q7Hk0HL' \
--data-raw '{
"amount": 6540,
"currency": "USD",
"confirm": true,
"capture_method": "manual",
"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",
"profile_id": "pro_doSItPZQZBbfoS0iEf81",
"business_country": "US",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "371449635398431",
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": "joseph Doe",
"card_cvc": "7373"
}
},
"routing": {
"type": "single",
"data": "adyen"
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "DE",
"first_name": "PiX"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "PiX"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}'
```
- ideal (Automatic Capture)
```
**Confirm Call:**
{
"client_secret": "{{client_secret}}",
"payment_method": "bank_redirect",
"payment_method_type": "ideal",
"payment_method_data": {
"bank_redirect": {
"ideal": {
"billing_details": {
"billing_name": "John Doe"
},
"bank_name": "n26",
"preferred_language": "en",
"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"
}
}
```
- Do any of the operation `REFUND, CANCEL, CAPTURE`
- Wait for Configured webhooks
- Do a sync for Success Scenario
**Outgoing Webhooks Example**
- Charged
<details><summary> Cards </summary>
<img src = "https://github.com/juspay/hyperswitch/assets/55536657/47c3d2c1-3e13-4490-b54a-220ce4fe3873">
</details>
<details><summary> Paypal </summary>
<img src = "https://github.com/juspay/hyperswitch/assets/55536657/e4b32b2e-152a-4f75-8559-8e26994528d6">
</details>
<details><summary> Klarna </summary>
<img src = "https://github.com/juspay/hyperswitch/assets/55536657/62851be5-2b37-4d18-933c-cec2f956a6d8">
</details>
<details><summary> Ideal </summary>
<img src = "https://github.com/juspay/hyperswitch/assets/55536657/dec43f75-4859-43fe-a296-3a76362ec144">
</details>
- Authorized
<details><summary> Cards </summary>
<img src = "https://github.com/juspay/hyperswitch/assets/55536657/6163f6fc-59ad-45da-86ee-9f847b5db5de">
</details>
<details><summary> Paypal </summary>
<img src = "https://github.com/juspay/hyperswitch/assets/55536657/94a1b125-06c1-4f47-9feb-37c551581bcf">
</details>
<details><summary> Klarna </summary>
<img src = "https://github.com/juspay/hyperswitch/assets/55536657/1875945d-e76c-43b8-9597-8dd9b89f7e76">
</details>
<details><summary> Cancelled </summary>
<img src = "https://github.com/juspay/hyperswitch/assets/55536657/1f24c3de-5e1a-4f13-aa72-4ac2f74b2a86">
</details>
<details><summary> Captured </summary>
<img src = "(https://github.com/juspay/hyperswitch/assets/55536657/e5d83e48-b70e-46f3-a815-6278878831a7">
</details>
<details><summary> Refunded </summary>
<img src = "(https://github.com/juspay/hyperswitch/assets/55536657/fef683dd-b4e2-498a-bc9a-6ef32206ef6c">
</details>
## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
a1fd36a1abea4d400386a00ccf182dfe9da5bcda
|
|
juspay/hyperswitch
|
juspay__hyperswitch-3948
|
Bug: fix: Enforce uniqueness of groups in custom role assignments
Permission groups should be unique while creating/updating custom role.
|
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index 6b25b692c12..643d8ac975e 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -2327,6 +2327,7 @@ pub enum RoleScope {
Debug,
Eq,
PartialEq,
+ Hash,
serde::Serialize,
serde::Deserialize,
strum::Display,
diff --git a/crates/router/src/utils/user_role.rs b/crates/router/src/utils/user_role.rs
index bb83b82f2da..c9d112f2566 100644
--- a/crates/router/src/utils/user_role.rs
+++ b/crates/router/src/utils/user_role.rs
@@ -1,3 +1,5 @@
+use std::collections::HashSet;
+
use api_models::user_role as user_role_api;
use common_enums::PermissionGroup;
use error_stack::ResultExt;
@@ -48,11 +50,18 @@ pub fn validate_role_groups(groups: &[PermissionGroup]) -> UserResult<()> {
.attach_printable("Role groups cannot be empty");
}
- if groups.contains(&PermissionGroup::OrganizationManage) {
+ let unique_groups: HashSet<_> = groups.iter().cloned().collect();
+
+ if unique_groups.contains(&PermissionGroup::OrganizationManage) {
return Err(UserErrors::InvalidRoleOperation.into())
.attach_printable("Organization manage group cannot be added to role");
}
+ if unique_groups.len() != groups.len() {
+ return Err(UserErrors::InvalidRoleOperation.into())
+ .attach_printable("Duplicate permission group found");
+ }
+
Ok(())
}
|
2024-03-04T13:37:03Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
Enforce uniqueness of groups while role create or 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
Currently duplicate groups are allowed while role create/update.
## How did you test it?
Try to create/update role with duplicate groups:
Create
```
curl --location 'http://localhost:8080/user/role' \
--header 'Authorization: Bearer JWT' \
--header 'Content-Type: application/json' \
--data '{
"role_name": "test007",
"groups": ["operations_view", "operations_manage", "operations_manage"],
"role_scope": "organization"
}'
```
Response:
```
{
"error": {
"type": "invalid_request",
"message": "User Role Operation Not Supported",
"code": "UR_23"
}
}
```
Update
```
curl --location --request PUT 'http://localhost:8080/user/role/role_DGLY2gKDdS48cFoY573Y' \
--header 'Authorization: Bearer JWT' \
--header 'Content-Type: application/json' \
--data '{
"groups": ["operations_view", "operations_view"]
}'
```
Response:
```
{
"error": {
"type": "invalid_request",
"message": "User Role Operation Not Supported",
"code": "UR_23"
}
}
```
## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
f132527490a7d8cd8469573d8e6856f33974959f
|
|
juspay/hyperswitch
|
juspay__hyperswitch-3943
|
Bug: Use mget to check in Blocklist Kv
Use MGet to check whether check multiple values in blocklist.
|
diff --git a/crates/router/src/services/authentication/blacklist.rs b/crates/router/src/services/authentication/blacklist.rs
index 346e563ee32..3a386c7793c 100644
--- a/crates/router/src/services/authentication/blacklist.rs
+++ b/crates/router/src/services/authentication/blacklist.rs
@@ -66,19 +66,25 @@ pub async fn check_user_in_blacklist<A: AppStateInfo>(
.map(|timestamp| timestamp.map_or(false, |timestamp| timestamp > token_issued_at))
}
-pub async fn check_role_in_blacklist<A: AppStateInfo>(
+pub async fn check_user_and_role_in_blacklist<A: AppStateInfo>(
state: &A,
+ user_id: &str,
role_id: &str,
token_expiry: u64,
) -> RouterResult<bool> {
- let token = format!("{}{}", ROLE_BLACKLIST_PREFIX, role_id);
+ let user_token = format!("{}{}", USER_BLACKLIST_PREFIX, user_id);
+ let role_token = format!("{}{}", ROLE_BLACKLIST_PREFIX, role_id);
let token_issued_at = expiry_to_i64(token_expiry - JWT_TOKEN_TIME_IN_SECS)?;
let redis_conn = get_redis_connection(state)?;
- redis_conn
- .get_key::<Option<i64>>(token.as_str())
+
+ Ok(redis_conn
+ .get_multiple_keys::<Vec<&str>, i64>(vec![user_token.as_str(), role_token.as_str()])
.await
- .change_context(ApiErrorResponse::InternalServerError)
- .map(|timestamp| timestamp.map_or(false, |timestamp| timestamp > token_issued_at))
+ .change_context(ApiErrorResponse::InternalServerError)?
+ .into_iter()
+ .max()
+ .flatten()
+ .map_or(false, |timestamp| timestamp > token_issued_at))
}
#[cfg(feature = "email")]
@@ -136,10 +142,7 @@ impl BlackList for AuthToken {
where
A: AppStateInfo + Sync,
{
- Ok(
- check_user_in_blacklist(state, &self.user_id, self.exp).await?
- || check_role_in_blacklist(state, &self.role_id, self.exp).await?,
- )
+ check_user_and_role_in_blacklist(state, &self.user_id, &self.role_id, self.exp).await
}
}
|
2024-03-04T13:00:49Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [x] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
Use MGet to check whether role or user is blacklisted in KV. Instead of checking user and role separately, MGet can help to do it in one call.
### 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
Enhancement
## How did you test it?
Singup --> Sigin --> Create a new role --> Invite new user with newly created role --> Sign In new user --> perform some operations which the user with assigned role can perform --> now update the role --> try performing same operation for the newly invited user. It won't be valid since role has been blocklist.
Can also check KV for blocklisted role_id and user_id.
Curls for singup/singin
curl --location 'http://localhost:8080/user/signup' \
--header 'Content-Type: application/json' \
--header 'Cookie: token=JWT' \
--data-raw '{
"email": "test121@juspay.in",
"password": "Test@12",
"country": "IN"
}
'
curl --location 'http://localhost:8080/user/signin' \
--header 'Content-Type: application/json' \
--header 'Cookie: token=JWT' \
--data-raw '{
"email": "test12345@juspay.in",
"password": "260e5c5c-dc96-4cb9-870c-eb18ab8ab577"
}'
Create Role:
curl --location 'http://localhost:8080/user/role' \
--header 'Authorization: Bearer JWT' \
--header 'Content-Type: application/json' \
--data '{
"role_name": "test",
"groups": ["operations_view", "operations_manage"],
"role_scope": "organization"
}'
Update Role:
curl --location --request PUT 'http://localhost:8080/user/role/role_QvY913dYo2b05D64bJ8l' \
--header 'Authorization: Bearer JWT' \
--header 'Content-Type: application/json' \
--data '{
"groups": ["operations_view"]
}'
## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
f132527490a7d8cd8469573d8e6856f33974959f
|
|
juspay/hyperswitch
|
juspay__hyperswitch-3944
|
Bug: feat: add caching for roles
Currently in authorization, we look at the resource and the role in the JWT to check whether that particular call is valid or not.
Upon the introduction of custom roles, this has increased db calls in the authorization phase as we need to get the permissions associated to a particular role. This will have unnecessary load on db and hits the performance of every api call.
To fix this, redis needs to be used to cache the permissions for a custom role.
|
diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs
index 8f77f72aad5..1641c0ae536 100644
--- a/crates/api_models/src/user.rs
+++ b/crates/api_models/src/user.rs
@@ -128,8 +128,6 @@ pub struct SwitchMerchantIdRequest {
pub merchant_id: String,
}
-pub type SwitchMerchantResponse = DashboardEntryResponse;
-
#[derive(serde::Deserialize, Debug, serde::Serialize)]
pub struct CreateInternalUserRequest {
pub name: Secret<String>,
diff --git a/crates/api_models/src/user_role.rs b/crates/api_models/src/user_role.rs
index 80d3861969a..411bf823a22 100644
--- a/crates/api_models/src/user_role.rs
+++ b/crates/api_models/src/user_role.rs
@@ -1,8 +1,6 @@
use common_enums::PermissionGroup;
use common_utils::pii;
-use crate::user::DashboardEntryResponse;
-
pub mod role;
#[derive(Debug, serde::Serialize)]
@@ -99,8 +97,6 @@ pub struct AcceptInvitationRequest {
pub need_dashboard_entry_response: Option<bool>,
}
-pub type AcceptInvitationResponse = DashboardEntryResponse;
-
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct DeleteUserRoleRequest {
pub email: pii::Email,
diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs
index 72f160990e5..87a16b73a8b 100644
--- a/crates/router/src/consts.rs
+++ b/crates/router/src/consts.rs
@@ -78,6 +78,8 @@ pub const EMAIL_TOKEN_TIME_IN_SECS: u64 = 60 * 60 * 24; // 1 day
#[cfg(feature = "email")]
pub const EMAIL_TOKEN_BLACKLIST_PREFIX: &str = "BET_";
+pub const ROLE_CACHE_PREFIX: &str = "CR_";
+
#[cfg(feature = "olap")]
pub const VERIFY_CONNECTOR_ID_PREFIX: &str = "conn_verify";
#[cfg(feature = "olap")]
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index b8b8cbd24c7..fceee528057 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -94,6 +94,7 @@ pub async fn signup(
)
.await?;
let token = utils::user::generate_jwt_auth_token(&state, &user_from_db, &user_role).await?;
+ utils::user_role::set_role_permissions_in_cache_by_user_role(&state, &user_role).await;
Ok(ApplicationResponse::Json(
utils::user::get_dashboard_entry_response(&state, user_from_db, user_role, token)?,
@@ -121,6 +122,7 @@ pub async fn signin_without_invite_checks(
let user_role = user_from_db.get_role_from_db(state.clone()).await?;
let token = utils::user::generate_jwt_auth_token(&state, &user_from_db, &user_role).await?;
+ utils::user_role::set_role_permissions_in_cache_by_user_role(&state, &user_role).await;
Ok(ApplicationResponse::Json(
utils::user::get_dashboard_entry_response(&state, user_from_db, user_role, token)?,
@@ -966,6 +968,8 @@ pub async fn accept_invite_from_email(
let token =
utils::user::generate_jwt_auth_token(&state, &user_from_db, &update_status_result).await?;
+ utils::user_role::set_role_permissions_in_cache_by_user_role(&state, &update_status_result)
+ .await;
Ok(ApplicationResponse::Json(
utils::user::get_dashboard_entry_response(
@@ -1044,7 +1048,7 @@ pub async fn switch_merchant_id(
state: AppState,
request: user_api::SwitchMerchantIdRequest,
user_from_token: auth::UserFromToken,
-) -> UserResponse<user_api::SwitchMerchantResponse> {
+) -> UserResponse<user_api::DashboardEntryResponse> {
if user_from_token.merchant_id == request.merchant_id {
return Err(UserErrors::InvalidRoleOperationWithMessage(
"User switching to same merchant id".to_string(),
@@ -1093,13 +1097,14 @@ pub async fn switch_merchant_id(
.organization_id;
let token = utils::user::generate_jwt_auth_token_with_custom_role_attributes(
- state,
+ &state,
&user,
request.merchant_id.clone(),
- org_id,
+ org_id.clone(),
user_from_token.role_id.clone(),
)
.await?;
+
(token, user_from_token.role_id)
} else {
let user_roles = state
@@ -1120,11 +1125,13 @@ pub async fn switch_merchant_id(
.attach_printable("User doesn't have access to switch")?;
let token = utils::user::generate_jwt_auth_token(&state, &user, user_role).await?;
+ utils::user_role::set_role_permissions_in_cache_by_user_role(&state, user_role).await;
+
(token, user_role.role_id.clone())
};
Ok(ApplicationResponse::Json(
- user_api::SwitchMerchantResponse {
+ user_api::DashboardEntryResponse {
token,
name: user.get_name(),
email: user.get_email(),
@@ -1266,6 +1273,7 @@ pub async fn verify_email_without_invite_checks(
.await
.map_err(|e| logger::error!(?e));
let token = utils::user::generate_jwt_auth_token(&state, &user_from_db, &user_role).await?;
+ utils::user_role::set_role_permissions_in_cache_by_user_role(&state, &user_role).await;
Ok(ApplicationResponse::Json(
utils::user::get_dashboard_entry_response(&state, user_from_db, user_role, token)?,
diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs
index 9dca9b43d96..b81b980c07a 100644
--- a/crates/router/src/core/user_role.rs
+++ b/crates/router/src/core/user_role.rs
@@ -159,6 +159,7 @@ pub async fn transfer_org_ownership(
.to_not_found_response(UserErrors::InvalidRoleOperation)?;
let token = utils::user::generate_jwt_auth_token(&state, &user_from_db, &user_role).await?;
+ utils::user_role::set_role_permissions_in_cache_by_user_role(&state, &user_role).await;
Ok(ApplicationResponse::Json(
utils::user::get_dashboard_entry_response(&state, user_from_db, user_role, token)?,
@@ -169,7 +170,7 @@ pub async fn accept_invitation(
state: AppState,
user_token: auth::UserWithoutMerchantFromToken,
req: user_role_api::AcceptInvitationRequest,
-) -> UserResponse<user_role_api::AcceptInvitationResponse> {
+) -> UserResponse<user_api::DashboardEntryResponse> {
let user_role = futures::future::join_all(req.merchant_ids.iter().map(|merchant_id| async {
state
.store
@@ -202,6 +203,8 @@ pub async fn accept_invitation(
.into();
let token = utils::user::generate_jwt_auth_token(&state, &user_from_db, &user_role).await?;
+ utils::user_role::set_role_permissions_in_cache_by_user_role(&state, &user_role).await;
+
return Ok(ApplicationResponse::Json(
utils::user::get_dashboard_entry_response(&state, user_from_db, user_role, token)?,
));
diff --git a/crates/router/src/services/authentication/blacklist.rs b/crates/router/src/services/authentication/blacklist.rs
index 346e563ee32..2ee8302be63 100644
--- a/crates/router/src/services/authentication/blacklist.rs
+++ b/crates/router/src/services/authentication/blacklist.rs
@@ -17,6 +17,7 @@ use crate::{
use crate::{
core::errors::{UserErrors, UserResult},
routes::AppState,
+ services::authorization as authz,
};
#[cfg(feature = "olap")]
@@ -47,10 +48,23 @@ pub async fn insert_role_in_blacklist(state: &AppState, role_id: &str) -> UserRe
date_time::now_unix_timestamp(),
expiry,
)
+ .await
+ .change_context(UserErrors::InternalServerError)?;
+ invalidate_role_cache(state, role_id)
.await
.change_context(UserErrors::InternalServerError)
}
+#[cfg(feature = "olap")]
+async fn invalidate_role_cache(state: &AppState, role_id: &str) -> RouterResult<()> {
+ let redis_conn = get_redis_connection(state)?;
+ redis_conn
+ .delete_key(authz::get_cache_key_from_role_id(role_id).as_str())
+ .await
+ .map(|_| ())
+ .change_context(ApiErrorResponse::InternalServerError)
+}
+
pub async fn check_user_in_blacklist<A: AppStateInfo>(
state: &A,
user_id: &str,
diff --git a/crates/router/src/services/authorization.rs b/crates/router/src/services/authorization.rs
index 2a516cc82d5..dc6d82d4e92 100644
--- a/crates/router/src/services/authorization.rs
+++ b/crates/router/src/services/authorization.rs
@@ -1,7 +1,13 @@
+use std::sync::Arc;
+
use common_enums::PermissionGroup;
+use error_stack::{IntoReport, ResultExt};
+use redis_interface::RedisConnectionPool;
+use router_env::logger;
use super::authentication::AuthToken;
use crate::{
+ consts,
core::errors::{ApiErrorResponse, RouterResult, StorageErrorExt},
routes::app::AppStateInfo,
};
@@ -19,22 +25,95 @@ pub async fn get_permissions<A>(
where
A: AppStateInfo + Sync,
{
- if let Some(role_info) = roles::predefined_roles::PREDEFINED_ROLES.get(token.role_id.as_str()) {
- Ok(get_permissions_from_groups(
- role_info.get_permission_groups(),
- ))
- } else {
- state
- .store()
- .find_role_by_role_id_in_merchant_scope(
- &token.role_id,
- &token.merchant_id,
- &token.org_id,
- )
- .await
- .map(|role| get_permissions_from_groups(&role.groups))
- .to_not_found_response(ApiErrorResponse::InvalidJwtToken)
+ if let Some(permissions) = get_permissions_from_predefined_roles(&token.role_id) {
+ return Ok(permissions);
+ }
+
+ if let Ok(permissions) = get_permissions_from_cache(state, &token.role_id)
+ .await
+ .map_err(|e| logger::error!("Failed to get permissions from cache {}", e))
+ {
+ return Ok(permissions);
}
+
+ let permissions =
+ get_permissions_from_db(state, &token.role_id, &token.merchant_id, &token.org_id).await?;
+
+ let token_expiry: i64 = token
+ .exp
+ .try_into()
+ .into_report()
+ .change_context(ApiErrorResponse::InternalServerError)?;
+ let cache_ttl = token_expiry - common_utils::date_time::now_unix_timestamp();
+
+ set_permissions_in_cache(state, &token.role_id, &permissions, cache_ttl)
+ .await
+ .map_err(|e| logger::error!("Failed to set permissions in cache {}", e))
+ .ok();
+ Ok(permissions)
+}
+
+async fn get_permissions_from_cache<A>(
+ state: &A,
+ role_id: &str,
+) -> RouterResult<Vec<permissions::Permission>>
+where
+ A: AppStateInfo + Sync,
+{
+ let redis_conn = get_redis_connection(state)?;
+
+ redis_conn
+ .get_and_deserialize_key(&get_cache_key_from_role_id(role_id), "Vec<Permission>")
+ .await
+ .change_context(ApiErrorResponse::InternalServerError)
+}
+
+pub fn get_cache_key_from_role_id(role_id: &str) -> String {
+ format!("{}{}", consts::ROLE_CACHE_PREFIX, role_id)
+}
+
+fn get_permissions_from_predefined_roles(role_id: &str) -> Option<Vec<permissions::Permission>> {
+ roles::predefined_roles::PREDEFINED_ROLES
+ .get(role_id)
+ .map(|role_info| get_permissions_from_groups(role_info.get_permission_groups()))
+}
+
+async fn get_permissions_from_db<A>(
+ state: &A,
+ role_id: &str,
+ merchant_id: &str,
+ org_id: &str,
+) -> RouterResult<Vec<permissions::Permission>>
+where
+ A: AppStateInfo + Sync,
+{
+ state
+ .store()
+ .find_role_by_role_id_in_merchant_scope(role_id, merchant_id, org_id)
+ .await
+ .map(|role| get_permissions_from_groups(&role.groups))
+ .to_not_found_response(ApiErrorResponse::InvalidJwtToken)
+}
+
+pub async fn set_permissions_in_cache<A>(
+ state: &A,
+ role_id: &str,
+ permissions: &Vec<permissions::Permission>,
+ expiry: i64,
+) -> RouterResult<()>
+where
+ A: AppStateInfo + Sync,
+{
+ let redis_conn = get_redis_connection(state)?;
+
+ redis_conn
+ .serialize_and_set_key_with_expiry(
+ &get_cache_key_from_role_id(role_id),
+ permissions,
+ expiry,
+ )
+ .await
+ .change_context(ApiErrorResponse::InternalServerError)
}
pub fn get_permissions_from_groups(groups: &[PermissionGroup]) -> Vec<permissions::Permission> {
@@ -62,3 +141,11 @@ pub fn check_authorization(
.into(),
)
}
+
+fn get_redis_connection<A: AppStateInfo>(state: &A) -> RouterResult<Arc<RedisConnectionPool>> {
+ state
+ .store()
+ .get_redis_conn()
+ .change_context(ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to get redis connection")
+}
diff --git a/crates/router/src/services/authorization/info.rs b/crates/router/src/services/authorization/info.rs
index d6a20b7f8ed..7b82e84d64c 100644
--- a/crates/router/src/services/authorization/info.rs
+++ b/crates/router/src/services/authorization/info.rs
@@ -187,7 +187,7 @@ fn get_group_description(group: PermissionGroup) -> &'static str {
"View Payments, Refunds, Mandates, Disputes and Customers"
}
PermissionGroup::OperationsManage => {
- "Create,modify and delete Payments, Refunds, Mandates, Disputes and Customers"
+ "Create, modify and delete Payments, Refunds, Mandates, Disputes and Customers"
}
PermissionGroup::ConnectorsView => {
"View connected Payment Processors, Payout Processors and Fraud & Risk Manager details"
diff --git a/crates/router/src/services/authorization/permissions.rs b/crates/router/src/services/authorization/permissions.rs
index 8d436618b32..edf9a40915c 100644
--- a/crates/router/src/services/authorization/permissions.rs
+++ b/crates/router/src/services/authorization/permissions.rs
@@ -1,6 +1,8 @@
use strum::Display;
-#[derive(PartialEq, Display, Clone, Debug, Copy, Eq, Hash)]
+#[derive(
+ PartialEq, Display, Clone, Debug, Copy, Eq, Hash, serde::Deserialize, serde::Serialize,
+)]
pub enum Permission {
PaymentRead,
PaymentWrite,
diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs
index d6e878456e8..1850eb4b81a 100644
--- a/crates/router/src/types/domain/user.rs
+++ b/crates/router/src/types/domain/user.rs
@@ -861,8 +861,11 @@ impl SignInWithSingleRoleStrategy {
async fn get_signin_response(self, state: &AppState) -> UserResult<user_api::SignInResponse> {
let token =
utils::user::generate_jwt_auth_token(state, &self.user, &self.user_role).await?;
+ utils::user_role::set_role_permissions_in_cache_by_user_role(state, &self.user_role).await;
+
let dashboard_entry_response =
utils::user::get_dashboard_entry_response(state, self.user, self.user_role, token)?;
+
Ok(user_api::SignInResponse::DashboardEntry(
dashboard_entry_response,
))
diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs
index c3b795d1a57..cfab331f148 100644
--- a/crates/router/src/utils/user.rs
+++ b/crates/router/src/utils/user.rs
@@ -87,7 +87,7 @@ pub async fn generate_jwt_auth_token(
}
pub async fn generate_jwt_auth_token_with_custom_role_attributes(
- state: AppState,
+ state: &AppState,
user: &UserFromStorage,
merchant_id: String,
org_id: String,
diff --git a/crates/router/src/utils/user_role.rs b/crates/router/src/utils/user_role.rs
index bb83b82f2da..a0ac1400582 100644
--- a/crates/router/src/utils/user_role.rs
+++ b/crates/router/src/utils/user_role.rs
@@ -1,11 +1,14 @@
use api_models::user_role as user_role_api;
use common_enums::PermissionGroup;
-use error_stack::ResultExt;
+use diesel_models::user_role::UserRole;
+use error_stack::{IntoReport, ResultExt};
+use router_env::logger;
use crate::{
+ consts,
core::errors::{UserErrors, UserResult},
routes::AppState,
- services::authorization::{permissions::Permission, roles},
+ services::authorization::{self as authz, permissions::Permission, roles},
types::domain,
};
@@ -83,3 +86,47 @@ pub async fn validate_role_name(
Ok(())
}
+
+pub async fn set_role_permissions_in_cache_by_user_role(
+ state: &AppState,
+ user_role: &UserRole,
+) -> bool {
+ set_role_permissions_in_cache_if_required(
+ state,
+ user_role.role_id.as_str(),
+ user_role.merchant_id.as_str(),
+ user_role.org_id.as_str(),
+ )
+ .await
+ .map_err(|e| logger::error!("Error setting permissions in cache {:?}", e))
+ .is_ok()
+}
+
+pub async fn set_role_permissions_in_cache_if_required(
+ state: &AppState,
+ role_id: &str,
+ merchant_id: &str,
+ org_id: &str,
+) -> UserResult<()> {
+ if roles::predefined_roles::PREDEFINED_ROLES.contains_key(role_id) {
+ return Ok(());
+ }
+
+ let role_info = roles::RoleInfo::from_role_id(state, role_id, merchant_id, org_id)
+ .await
+ .change_context(UserErrors::InternalServerError)
+ .attach_printable("Error getting role_info from role_id")?;
+
+ authz::set_permissions_in_cache(
+ state,
+ role_id,
+ &role_info.get_permissions_set().into_iter().collect(),
+ consts::JWT_TOKEN_TIME_IN_SECS
+ .try_into()
+ .into_report()
+ .change_context(UserErrors::InternalServerError)?,
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)
+ .attach_printable("Error setting permissions in redis")
+}
|
2024-03-04T13:11:08Z
|
## 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 caching for custom roles to reduce db calls and improve efficiency.
### 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 #3944
## 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)?
-->
Postman.
This cannot be tested in hosted environment as redis is not accessible directly but can be tested in local environment. So, writing the instructions for local testing here.
1. Signin with a user who has assigned a custom role (not a predefined role)
```
curl --location 'http://localhost:8080/user/signin' \
--header 'Content-Type: application/json' \
--data-raw '{
"email": "user email",
"password": "password"
}'
```
You will get the following response
```
{
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiOWQyOTQzMDgtYjhjMC00ZTU1LTkwYjgtMjA5ZGZkNjFhZWE4IiwibWVyY2hhbnRfaWQiOiJtZXJjaGFudF8xNzA5MTI1MjczIiwicm9sZV9pZCI6InJvbGVfTmRDVW12WUIwalhCRmpwUW8ydEUiLCJleHAiOjE3MDk3MjkwNzcsIm9yZ19pZCI6Im9yZ181UEluV2RTN2FJc0FGa3g5dFUxWCJ9.Cf7ascQFk6-1USmhJlkk-B9gu0v6qQ-07SXCjZw6wEU",
"merchant_id": "merchant_1709125273",
"name": "user name",
"email": "user email",
"verification_days_left": null,
"user_role": "role_NdCUmvYB0jXBFjpQo2tE"
}
```
Notice that `user_role` has a `role_id` which starts with `role_`. That means this user has been assigned a custom role.
2. Now run `redis_cli` command in the terminal.
3. In the prompt, execute `keys *` command. You should get the output that looks like this
```
1) "CR_role_NdCUmvYB0jXBFjpQo2tE"
2) "123"
3) "accounts"
4) "234"
```
Notice that there is a key that starts with `CR_` and the remaining part matches with the `role_id` that we got in the signin response.
## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
f132527490a7d8cd8469573d8e6856f33974959f
|
|
juspay/hyperswitch
|
juspay__hyperswitch-3942
|
Bug: Set the PM as default if there is no Default PM for a customer
|
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index ce7f48405e2..712b9a0edd7 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -84,7 +84,8 @@ pub async fn create_payment_method(
payment_method_data: Option<Encryption>,
key_store: &domain::MerchantKeyStore,
) -> errors::CustomResult<storage::PaymentMethod, errors::ApiErrorResponse> {
- db.find_customer_by_customer_id_merchant_id(customer_id, merchant_id, key_store)
+ let customer = db
+ .find_customer_by_customer_id_merchant_id(customer_id, merchant_id, key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;
@@ -106,6 +107,17 @@ pub async fn create_payment_method(
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to add payment method in db")?;
+ if customer.default_payment_method_id.is_none() {
+ let _ = set_default_payment_method(
+ db,
+ merchant_id.to_string(),
+ key_store.clone(),
+ customer_id,
+ payment_method_id.to_owned(),
+ )
+ .await
+ .map_err(|err| logger::error!(error=?err,"Failed to set the payment method as default"));
+ }
Ok(response)
}
@@ -3080,20 +3092,15 @@ async fn get_bank_account_connector_details(
}
}
pub async fn set_default_payment_method(
- state: routes::AppState,
- merchant_account: domain::MerchantAccount,
+ db: &dyn db::StorageInterface,
+ merchant_id: String,
key_store: domain::MerchantKeyStore,
customer_id: &str,
payment_method_id: String,
) -> errors::RouterResponse<CustomerDefaultPaymentMethodResponse> {
- let db = &*state.store;
//check for the customer
let customer = db
- .find_customer_by_customer_id_merchant_id(
- customer_id,
- &merchant_account.merchant_id,
- &key_store,
- )
+ .find_customer_by_customer_id_merchant_id(customer_id, &merchant_id, &key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;
// check for the presence of payment_method
@@ -3103,8 +3110,7 @@ pub async fn set_default_payment_method(
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
utils::when(
- payment_method.customer_id != customer_id
- && payment_method.merchant_id != merchant_account.merchant_id,
+ payment_method.customer_id != customer_id || payment_method.merchant_id != merchant_id,
|| {
Err(errors::ApiErrorResponse::PreconditionFailed {
message: "The payment_method_id is not valid".to_string(),
@@ -3124,14 +3130,14 @@ pub async fn set_default_payment_method(
)?;
let customer_update = CustomerUpdate::UpdateDefaultPaymentMethod {
- default_payment_method_id: Some(payment_method_id.clone()),
+ default_payment_method_id: Some(payment_method_id.to_owned()),
};
// update the db with the default payment method id
let updated_customer_details = db
.update_customer_by_customer_id_merchant_id(
customer_id.to_owned(),
- merchant_account.merchant_id,
+ merchant_id.to_owned(),
customer_update,
&key_store,
)
diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs
index 1f793e2e185..baf395b230c 100644
--- a/crates/router/src/core/payments/tokenization.rs
+++ b/crates/router/src/core/payments/tokenization.rs
@@ -348,6 +348,7 @@ where
} else {
None
};
+
resp.payment_method_id = generate_id(consts::ID_LENGTH, "pm");
payment_methods::cards::create_payment_method(
db,
diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs
index 5469f981659..939cfaf93dc 100644
--- a/crates/router/src/routes/payment_methods.rs
+++ b/crates/router/src/routes/payment_methods.rs
@@ -275,15 +275,16 @@ pub async fn default_payment_method_set_api(
Ok(auth) => auth,
Err(err) => return api::log_and_return_error_response(err),
};
+ let db = &*state.store.clone();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
- |state, auth: auth::AuthenticationData, default_payment_method| {
+ |_state, auth: auth::AuthenticationData, default_payment_method| {
cards::set_default_payment_method(
- state,
- auth.merchant_account,
+ db,
+ auth.merchant_account.merchant_id,
auth.key_store,
&customer_id,
default_payment_method.payment_method_id,
|
2024-03-05T19:07:00Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [x] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
Set the initial payment method as default until its explicitly set
### 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 an MA and a MCA
- Do a save card payment
- Do a ListPaymentMethodsForCustomers the default flag would be set to true for the initial card
- Do a save card payment, with other card , its default flag would be set to false, until explicitly set to true , using the endpoint `/customers/:customer_id/payment_methods/:payment_method_id/default`
```
curl --location --request POST 'http://localhost:8080/customers/{customer_id}/payment_methods/{payment_method_id}/set' \
--header 'Accept: application/json' \
--header 'api-key: epk_bf2209db8af14c04b811bce74e0d1202'
```
<img width="1296" alt="Screenshot 2024-03-06 at 12 19 31 AM" src="https://github.com/juspay/hyperswitch/assets/55580080/0fda5a3c-4f3a-4675-9b0c-b82958d28fe9">
## 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
|
1a8056799c7c2b486044b403fff2e74310c98c44
|
|
juspay/hyperswitch
|
juspay__hyperswitch-3957
|
Bug: Disallow deletion of default payment method for a customer
Should not allow deletion of the default_payment_method of a customer.
Error Message: "Cannot delete the default payment method"
Merchant Error Handling: "Retry after setting another PM as default"
|
diff --git a/crates/router/src/compatibility/stripe/errors.rs b/crates/router/src/compatibility/stripe/errors.rs
index d28e988a039..c1f8b5e9c75 100644
--- a/crates/router/src/compatibility/stripe/errors.rs
+++ b/crates/router/src/compatibility/stripe/errors.rs
@@ -251,6 +251,8 @@ pub enum StripeErrorCode {
InvalidConnectorConfiguration { config: String },
#[error(error_type = StripeErrorType::HyperswitchError, code = "HE_01", message = "Failed to convert currency to minor unit")]
CurrencyConversionFailed,
+ #[error(error_type = StripeErrorType::InvalidRequestError, code = "IR_25", message = "Cannot delete the default payment method")]
+ PaymentMethodDeleteFailed,
// [#216]: https://github.com/juspay/hyperswitch/issues/216
// Implement the remaining stripe error codes
@@ -618,6 +620,7 @@ impl From<errors::ApiErrorResponse> for StripeErrorCode {
Self::InvalidConnectorConfiguration { config }
}
errors::ApiErrorResponse::CurrencyConversionFailed => Self::CurrencyConversionFailed,
+ errors::ApiErrorResponse::PaymentMethodDeleteFailed => Self::PaymentMethodDeleteFailed,
}
}
}
@@ -686,7 +689,8 @@ impl actix_web::ResponseError for StripeErrorCode {
| Self::DuplicateCustomer
| Self::PaymentMethodUnactivated
| Self::InvalidConnectorConfiguration { .. }
- | Self::CurrencyConversionFailed => StatusCode::BAD_REQUEST,
+ | Self::CurrencyConversionFailed
+ | Self::PaymentMethodDeleteFailed => StatusCode::BAD_REQUEST,
Self::RefundFailed
| Self::PayoutFailed
| Self::PaymentLinkNotFound
diff --git a/crates/router/src/core/errors/api_error_response.rs b/crates/router/src/core/errors/api_error_response.rs
index f9ed61e0f1b..46c90d776d4 100644
--- a/crates/router/src/core/errors/api_error_response.rs
+++ b/crates/router/src/core/errors/api_error_response.rs
@@ -252,6 +252,8 @@ pub enum ApiErrorResponse {
InvalidConnectorConfiguration { config: String },
#[error(error_type = ErrorType::ValidationError, code = "HE_01", message = "Failed to convert currency to minor unit")]
CurrencyConversionFailed,
+ #[error(error_type = ErrorType::InvalidRequestError, code = "IR_25", message = "Cannot delete the default payment method")]
+ PaymentMethodDeleteFailed,
}
impl PTError for ApiErrorResponse {
diff --git a/crates/router/src/core/errors/transformers.rs b/crates/router/src/core/errors/transformers.rs
index ee63074544c..ce5253051e1 100644
--- a/crates/router/src/core/errors/transformers.rs
+++ b/crates/router/src/core/errors/transformers.rs
@@ -281,6 +281,9 @@ impl ErrorSwitch<api_models::errors::types::ApiErrorResponse> for ApiErrorRespon
Self::CurrencyConversionFailed => {
AER::Unprocessable(ApiError::new("HE", 2, "Failed to convert currency to minor unit", None))
}
+ Self::PaymentMethodDeleteFailed => {
+ AER::BadRequest(ApiError::new("IR", 25, "Cannot delete the default payment method", None))
+ }
}
}
}
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index ce7f48405e2..7344cd09a5a 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -3365,6 +3365,7 @@ pub async fn delete_payment_method(
state: routes::AppState,
merchant_account: domain::MerchantAccount,
pm_id: api::PaymentMethodId,
+ key_store: domain::MerchantKeyStore,
) -> errors::RouterResponse<api::PaymentMethodDeleteResponse> {
let db = state.store.as_ref();
let key = db
@@ -3372,6 +3373,21 @@ pub async fn delete_payment_method(
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
+ let customer = db
+ .find_customer_by_customer_id_merchant_id(
+ &key.customer_id,
+ &merchant_account.merchant_id,
+ &key_store,
+ )
+ .await
+ .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),
+ || Err(errors::ApiErrorResponse::PaymentMethodDeleteFailed),
+ )?;
+
if key.payment_method == enums::PaymentMethod::Card {
let response = delete_card_from_locker(
&state,
diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs
index 5469f981659..c0c79bde0cd 100644
--- a/crates/router/src/routes/payment_methods.rs
+++ b/crates/router/src/routes/payment_methods.rs
@@ -253,7 +253,9 @@ pub async fn payment_method_delete_api(
state,
&req,
pm,
- |state, auth, req| cards::delete_payment_method(state, auth.merchant_account, req),
+ |state, auth, req| {
+ cards::delete_payment_method(state, auth.merchant_account, req, auth.key_store)
+ },
&auth::ApiKeyAuth,
api_locking::LockAction::NotApplicable,
))
|
2024-03-05T11:43:51Z
|
## 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 -->
If a payment method is set as a default payment method for a customer and it is tried to be deleted, we throw a invalid request 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).
-->
## 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. Store a card or any other payment method
2. Set that payment method as default
```
curl --location --request POST 'http://localhost:8080/customers/cus_aXfFGQOFT7JFU47GYhZK/payment_methods/pm_37h7qElY2aTWBEPSgovJ/default' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: abc' \
--data ''
```
3. Now try to delete that default payment method
```
curl --location --request DELETE 'http://localhost:8080/payment_methods/pm_37h7qElY2aTWBEPSgovJ' \
--header 'Accept: application/json' \
--header 'api-key: abc'
```

## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
c65729adc9009f046398312a16841532fdc177da
|
|
juspay/hyperswitch
|
juspay__hyperswitch-3937
|
Bug: [FEATURE] : [Coinbase][Cryptopay] mask pii information in connector request and response
### Feature Description
Mask pii information passed and received in the connector request and response
### Possible Implementation
Refactor all sensitive response and request fields secret
### 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/coinbase/transformers.rs b/crates/router/src/connector/coinbase/transformers.rs
index 5b3b6f63278..f02984136bd 100644
--- a/crates/router/src/connector/coinbase/transformers.rs
+++ b/crates/router/src/connector/coinbase/transformers.rs
@@ -21,7 +21,7 @@ pub struct LocalPrice {
#[derive(Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
pub struct Metadata {
pub customer_id: Option<String>,
- pub customer_name: Option<String>,
+ pub customer_name: Option<Secret<String>>,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
@@ -335,7 +335,7 @@ pub enum WebhookEventType {
pub struct CoinbasePaymentResponseData {
pub id: String,
pub code: String,
- pub name: Option<String>,
+ pub name: Option<Secret<String>>,
pub utxo: bool,
pub pricing: HashMap<String, OverpaymentAbsoluteThreshold>,
pub fee_rate: f64,
@@ -355,7 +355,7 @@ pub struct CoinbasePaymentResponseData {
pub fees_settled: bool,
pub pricing_type: String,
pub redirect_url: String,
- pub support_email: String,
+ pub support_email: pii::Email,
pub brand_logo_url: String,
pub offchain_eligible: bool,
pub organization_name: String,
diff --git a/crates/router/src/connector/cryptopay/transformers.rs b/crates/router/src/connector/cryptopay/transformers.rs
index d4697e3ba14..635d4a66c26 100644
--- a/crates/router/src/connector/cryptopay/transformers.rs
+++ b/crates/router/src/connector/cryptopay/transformers.rs
@@ -222,7 +222,7 @@ pub struct CryptopayPaymentResponseData {
pub customer_id: Option<String>,
pub status: CryptopayPaymentStatus,
pub status_context: Option<String>,
- pub address: Option<String>,
+ pub address: Option<Secret<String>>,
pub network: Option<String>,
pub uri: Option<String>,
pub price_amount: Option<String>,
|
2024-03-04T10:45:14Z
|
## 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 -->
Mask pii information passed and received in the connector request and response for coinbase and cryptopay.
## Test Case
<!--
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 crypto payment with coinbase
_Note:Metadata not passed in dashboard_
Metadata to be included in Connector Create
```
"metadata": {
"pricing_type": "fixed_price"
},
```
```
{
"amount": 200,
"currency": "GBP",
"confirm": true,
"capture_method": "manual",
"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": "no_three_ds",
"return_url": "https://google.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,application/signed-exchange;v=b3",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": false,
"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"
},
"payment_method": "crypto",
"payment_method_type": "crypto_currency",
"payment_method_data": {
"crypto": {
"pay_currency": "USD"
}
}
}
```
2. Create a payment in Cryptopay
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_JsfXOsrNjUW5OCAb7RKI6Fzg1XlF8ajI48gr2AVcgxnGnqp2Cvv4WnFY8RWPTIhD' \
--data-raw '{
"amount": 200,
"currency": "INR",
"confirm": true,
"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": "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"
}
},
"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,application/signed-exchange;v=b3",
"language": "nl-NL",
"color_depth": 24,
"screen_height": 723,
"screen_width": 1536,
"time_zone": 0,
"java_enabled": false,
"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"
},
"payment_method": "crypto",
"payment_method_type": "crypto_currency",
"payment_method_data": {
"crypto": {
"pay_currency": "XRP"
}
}
}'
```
4. Check if pii data in `masked_response` is masked
```
curl --location '{{base_url}}/analytics/v1/connector_event_logs?type=Payment&payment_id={{payment_id}}' \
--header 'sec-ch-ua: "Not A(Brand";v="99", "Google Chrome";v="121", "Chromium";v="121"' \
--header 'sec-ch-ua-mobile: ?0' \
--header 'authorization: Bearer JWT_token' \
--header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36' \
--header 'Content-Type: application/json' \
--header 'Referer: https://integ.hyperswitch.io/' \
--header 'api-key: {{api-key}}' \
--header 'sec-ch-ua-platform: "macOS"'
```
Coinbase Response
```
masked_response\":\"{\\\"data\\\":{\\\"id\\\":\\\"b74480cf-c92d-44b2-af40-5a6a91a7f910\\\",\\\"code\\\":\\\"GZ62GFRC\\\",\\\"name\\\":null,\\\"utxo\\\":false,\\\"pricing\\\":{\\\"polygon\\\":{\\\"amount\\\":\\\"226.804602000\\\",\\\"currency\\\":\\\"PMATIC\\\"},\\\"bitcoin\\\":{\\\"amount\\\":\\\"0.00385362\\\",\\\"currency\\\":\\\"BTC\\\"},\\\"bitcoincash\\\":{\\\"amount\\\":\\\"0.63153123\\\",\\\"currency\\\":\\\"BCH\\\"},\\\"usdc\\\":{\\\"amount\\\":\\\"254.690228\\\",\\\"currency\\\":\\\"USDC\\\"},\\\"pweth\\\":{\\\"amount\\\":\\\"0.067417426548866693\\\",\\\"currency\\\":\\\"PWETH\\\"},\\\"pusdc\\\":{\\\"amount\\\":\\\"254.690228\\\",\\\"currency\\\":\\\"PUSDC\\\"},\\\"apecoin\\\":{\\\"amount\\\":\\\"115.899990075346566553\\\",\\\"currency\\\":\\\"APE\\\"},\\\"tether\\\":{\\\"amount\\\":\\\"254.612571\\\",\\\"currency\\\":\\\"USDT\\\"},\\\"dogecoin\\\":{\\\"amount\\\":\\\"1690.60888278\\\",\\\"currency\\\":\\\"DOGE\\\"},\\\"local\\\":{\\\"amount\\\":\\\"200.00\\\",\\\"currency\\\":\\\"GBP\\\"},\\\"dai\\\":{\\\"amount\\\":\\\"254.728437456192508876\\\",\\\"currency\\\":\\\"DAI\\\"},\\\"polusdc\\\":{\\\"amount\\\":\\\"254.690228\\\",\\\"currency\\\":\\\"POLUSDC\\\"},\\\"ethereum\\\":{\\\"amount\\\":\\\"0.067372000\\\",\\\"currency\\\":\\\"ETH\\\"},\\\"shibainu\\\":{\\\"amount\\\":\\\"8225100.216068919102212175\\\",\\\"currency\\\":\\\"SHIB\\\"},\\\"litecoin\\\":{\\\"amount\\\":\\\"3.00803387\\\",\\\"currency\\\":\\\"LTC\\\"}},\\\"fee_rate\\\":0.01,\\\"logo_url\\\":\\\"\\\",\\\"metadata\\\":{\\\"customer_id\\\":null,\\\"customer_name\\\":null},\\\"payments\\\":[],\\\"resource\\\":\\\"charge\\\",\\\"timeline\\\":[{\\\"status\\\":\\\"NEW\\\",\\\"context\\\":null,\\\"time\\\":\\\"2024-03-07T07:33:35Z\\\",\\\"payment\\\":null}],\\\"pwcb_only\\\":false,\\\"cancel_url\\\":\\\"http://localhost:8080/payments/pay_wCjb90F5sNJD1qlvfxAs/merchant_1709796607/redirect/response/coinbase\\\",\\\"created_at\\\":\\\"2024-03-07T07:33:35Z\\\",\\\"expires_at\\\":\\\"2024-03-07T08:33:35Z\\\",\\\"hosted_url\\\":\\\"https://commerce.coinbase.com/charges/GZ62GFRC\\\",\\\"brand_color\\\":\\\"#122332\\\",\\\"description\\\":\\\"Its my first payment request\\\",\\\"confirmed_at\\\":null,\\\"fees_settled\\\":true,\\\"pricing_type\\\":\\\"fixed_price\\\",\\\"redirect_url\\\":\\\"http://localhost:8080/payments/pay_wCjb90F5sNJD1qlvfxAs/merchant_1709796607/redirect/response/coinbase\\\",\\\"support_email\\\":\\\\"********@gmail.com\\\",\\\"brand_logo_url\\\":\\\"\\\",\\\"offchain_eligible\\\":false,\\\"organization_name\\\":\\\"\\\",\\\"payment_threshold\\\":{\\\"overpayment_absolute_threshold\\\":{\\\"amount\\\":\\\"5.00\\\",\\\"currency\\\":\\\"USD\\\"},\\\"overpayment_relative_threshold\\\":\\\"0.005\\\",\\\"underpayment_absolute_threshold\\\":{\\\"amount\\\":\\\"5.00\\\",\\\"currency\\\":\\\"USD\\\"},\\\"underpayment_relative_threshold\\\":\\\"0.005\\\"},\\\"coinbase_managed_merchant\\\":false}}
```
Cryptopay Response
```
masked_response\":\"{\\\"data\\\":{\\\"id\\\":\\\"5b837b10-6595-4e19-9ad8-188a17392c0e\\\",\\\"custom_id\\\":\\\"pay_uikX1Kbhlpvo06b0qJk1_1\\\",\\\"customer_id\\\":null,\\\"status\\\":\\\"new\\\",\\\"status_context\\\":null,\\\"address\\\":\\\"*** alloc::string::String ***\\\",\\\"network\\\":\\\"ripple\\\",\\\"uri\\\":\\\"ripple:rfCb49HbVfBLtoeec99APnYfKYu2uLoF35?amount=0.03804&dt=1273215618\\\",\\\"price_amount\\\":\\\"2.0\\\",\\\"price_currency\\\":\\\"INR\\\",\\\"pay_amount\\\":\\\"0.03804\\\",\\\"pay_currency\\\":\\\"XRP\\\",\\\"fee\\\":\\\"0.02\\\",\\\"fee_currency\\\":\\\"INR\\\",\\\"paid_amount\\\":\\\"0.0\\\",\\\"name\\\":null,\\\"description\\\":null,\\\"success_redirect_url\\\":\\\"http://localhost:8080/payments/pay_uikX1Kbhlpvo06b0qJk1/merchant_1709796432/redirect/response/cryptopay\\\",\\\"unsuccess_redirect_url\\\":\\\"http://localhost:8080/payments/pay_uikX1Kbhlpvo06b0qJk1/merchant_1709796432/redirect/response/cryptopay\\\",\\\"hosted_page_url\\\":\\\"https://hosted-business-sandbox.cryptopay.me/invoices/5b837b10-6595-4e19-9ad8-188a17392c0e\\\",\\\"created_at\\\":\\\"2024-03-07T07:27:27+00:00\\\",\\\"expires_at\\\":\\\"2024-03-07T07:37:27+00:00\\\"}}
```
## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
8c103c0f8e838a899a0c1207c88fa7617b37f138
|
|
juspay/hyperswitch
|
juspay__hyperswitch-3933
|
Bug: [FEATURE] : [Trustpay][Volt] mask pii information in connector request and response
### Feature Description
Mask pii information passed and received in the connector request and response
### Possible Implementation
Refactor all sensitive response and request fields secret
### 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/trustpay/transformers.rs b/crates/router/src/connector/trustpay/transformers.rs
index 71286bda3f1..d5b65bb9975 100644
--- a/crates/router/src/connector/trustpay/transformers.rs
+++ b/crates/router/src/connector/trustpay/transformers.rs
@@ -6,7 +6,7 @@ use common_utils::{
pii::{self, Email},
};
use error_stack::{report, ResultExt};
-use masking::{PeekInterface, Secret};
+use masking::{ExposeInterface, PeekInterface, Secret};
use reqwest::Url;
use serde::{Deserialize, Serialize};
@@ -1069,8 +1069,8 @@ pub struct GooglePayTransactionInfo {
#[derive(Clone, Default, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GooglePayMerchantInfo {
- pub merchant_name: String,
- pub merchant_id: String,
+ pub merchant_name: Secret<String>,
+ pub merchant_id: Secret<String>,
}
#[derive(Clone, Default, Debug, Deserialize, Serialize)]
@@ -1086,7 +1086,7 @@ pub struct GooglePayAllowedPaymentMethods {
#[serde(rename_all = "camelCase")]
pub struct GpayTokenParameters {
pub gateway: String,
- pub gateway_merchant_id: String,
+ pub gateway_merchant_id: Secret<String>,
}
#[derive(Clone, Default, Debug, Deserialize, Serialize)]
@@ -1291,8 +1291,8 @@ impl From<GooglePayTransactionInfo> for api_models::payments::GpayTransactionInf
impl From<GooglePayMerchantInfo> for api_models::payments::GpayMerchantInfo {
fn from(value: GooglePayMerchantInfo) -> Self {
Self {
- merchant_id: Some(value.merchant_id),
- merchant_name: value.merchant_name,
+ merchant_id: Some(value.merchant_id.expose()),
+ merchant_name: value.merchant_name.expose(),
}
}
}
@@ -1329,7 +1329,7 @@ impl From<GpayTokenParameters> for api_models::payments::GpayTokenParameters {
fn from(value: GpayTokenParameters) -> Self {
Self {
gateway: value.gateway,
- gateway_merchant_id: Some(value.gateway_merchant_id),
+ gateway_merchant_id: Some(value.gateway_merchant_id.expose()),
stripe_version: None,
stripe_publishable_key: None,
}
diff --git a/crates/router/src/connector/volt/transformers.rs b/crates/router/src/connector/volt/transformers.rs
index ccb482d5b7c..8e63f5d6ef1 100644
--- a/crates/router/src/connector/volt/transformers.rs
+++ b/crates/router/src/connector/volt/transformers.rs
@@ -190,7 +190,7 @@ pub struct VoltAuthUpdateResponse {
pub access_token: Secret<String>,
pub token_type: String,
pub expires_in: i64,
- pub refresh_token: String,
+ pub refresh_token: Secret<String>,
}
impl<F, T> TryFrom<types::ResponseRouterData<F, VoltAuthUpdateResponse, T, types::AccessToken>>
|
2024-03-04T09:30:38Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [x] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Mask pii information passed and received in the connector request and response for Trustpay, Volt and Wise.
## Test Case
<!--
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 Gpay payment with trustpay
Generate toke from : https://jsfiddle.net/1agu74ve/1/
```
const tokenizationSpecification = {
type: 'PAYMENT_GATEWAY',
parameters: {
"gateway": "trustpay",
"gatewayMerchantId": "{{merchant_id}}"
}
};
```
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key:{{}}' \
--data-raw '{
"amount": 1800,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"customer_id": "CustomerX",
"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": "google_pay",
"payment_method_data": {
"wallet": {
"google_pay": {
"type": "CARD",
"description": "Visa •••• 1111",
"info": {
"card_network": "VISA",
"card_details": "1111"
},
"tokenization_data": {
"type": "PAYMENT_GATEWAY",
"token": "{{token}}"
}
}
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "Dubai",
"zip": "94122",
"country": "AE",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+97"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "AE",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"metadata": {
"count_tickets": 1,
"transaction_number": "5590043"
}
}'
```
2. Refresh Token flow of volt
_Note: can't be tested not implemented_
3. Check if all the sensitive data in the `masked_response` is masked
```
curl --location '{{base_url}}/analytics/v1/connector_event_logs?type=Payment&payment_id={{payment_id}}' \
--header 'sec-ch-ua: "Not A(Brand";v="99", "Google Chrome";v="121", "Chromium";v="121"' \
--header 'sec-ch-ua-mobile: ?0' \
--header 'authorization: Bearer JWT_token' \
--header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36' \
--header 'Content-Type: application/json' \
--header 'Referer: https://integ.hyperswitch.io/' \
--header 'api-key: {{api-key}}' \
--header 'sec-ch-ua-platform: "macOS"'
```
Response of Trustpay Gpay
```
"masked_response\":\"{\\\"secrets\\\":{\\\"display\\\":\\\"*** alloc::string::String ***\\\",\\\"payment\\\":\\\"*** alloc::string::String ***\\\"},\\\"googleInitResultData\\\":{\\\"merchantInfo\\\":{\\\"merchantName\\\":\\\"*** alloc::string::String ***\\\",\\\"merchantId\\\":\\\"*** alloc::string::String ***\\\"},\\\"allowedPaymentMethods\\\":[{\\\"type\\\":\\\"CARD\\\",\\\"parameters\\\":{\\\"allowedAuthMethods\\\":[\\\"PAN_ONLY\\\",\\\"CRYPTOGRAM_3DS\\\"],\\\"allowedCardNetworks\\\":[\\\"MASTERCARD\\\",\\\"VISA\\\"]},\\\"tokenizationSpecification\\\":{\\\"type\\\":\\\"PAYMENT_GATEWAY\\\",\\\"parameters\\\":{\\\"gateway\\\":\\\"trustpay\\\",\\\"gatewayMerchantId\\\":\\\"*** alloc::string::String ***\\\"}}}],\\\"transactionInfo\\\":{\\\"countryCode\\\":\\\"IN\\\",\\\"currencyCode\\\":\\\"USD\\\",\\\"totalPriceStatus\\\":\\\"FINAL\\\",\\\"totalPrice\\\":\\\"18.00\\\"}}
```
## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
f132527490a7d8cd8469573d8e6856f33974959f
|
|
juspay/hyperswitch
|
juspay__hyperswitch-3934
|
Bug: [FEATURE] : [Worldline][Worldpay][Zen] mask pii information in connector request and response
### Feature Description
Mask pii information passed and received in the connector request and response
### Possible Implementation
Refactor all sensitive response and request fields secret
### 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/masking/src/serde.rs b/crates/masking/src/serde.rs
index a96a87f05c8..94c60eba3cf 100644
--- a/crates/masking/src/serde.rs
+++ b/crates/masking/src/serde.rs
@@ -27,6 +27,7 @@ pub trait SerializableSecret: Serialize {}
impl SerializableSecret for Value {}
impl SerializableSecret for u8 {}
impl SerializableSecret for u16 {}
+impl SerializableSecret for i8 {}
impl SerializableSecret for i32 {}
impl<'de, T, I> Deserialize<'de> for Secret<T, I>
diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs
index 996e06adfc4..1765bb3eeae 100644
--- a/crates/router/src/connector/utils.rs
+++ b/crates/router/src/connector/utils.rs
@@ -813,6 +813,8 @@ pub trait CardData {
fn get_expiry_date_as_mmyyyy(&self, delimiter: &str) -> Secret<String>;
fn get_expiry_year_4_digit(&self) -> Secret<String>;
fn get_expiry_date_as_yymm(&self) -> Result<Secret<String>, errors::ConnectorError>;
+ fn get_expiry_month_as_i8(&self) -> Result<Secret<i8>, Error>;
+ fn get_expiry_year_as_i32(&self) -> Result<Secret<i32>, Error>;
}
impl CardData for api::Card {
@@ -870,6 +872,24 @@ impl CardData for api::Card {
let month = self.card_exp_month.clone().expose();
Ok(Secret::new(format!("{year}{month}")))
}
+ fn get_expiry_month_as_i8(&self) -> Result<Secret<i8>, Error> {
+ self.card_exp_month
+ .peek()
+ .clone()
+ .parse::<i8>()
+ .into_report()
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)
+ .map(Secret::new)
+ }
+ fn get_expiry_year_as_i32(&self) -> Result<Secret<i32>, Error> {
+ self.card_exp_year
+ .peek()
+ .clone()
+ .parse::<i32>()
+ .into_report()
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)
+ .map(Secret::new)
+ }
}
#[track_caller]
diff --git a/crates/router/src/connector/worldline/transformers.rs b/crates/router/src/connector/worldline/transformers.rs
index 1eb22fc52d2..7a9a43eedc6 100644
--- a/crates/router/src/connector/worldline/transformers.rs
+++ b/crates/router/src/connector/worldline/transformers.rs
@@ -95,11 +95,11 @@ pub struct Name {
pub struct Shipping {
pub city: Option<String>,
pub country_code: Option<api_enums::CountryAlpha2>,
- pub house_number: Option<String>,
+ pub house_number: Option<Secret<String>>,
pub name: Option<Name>,
pub state: Option<Secret<String>>,
pub state_code: Option<String>,
- pub street: Option<String>,
+ pub street: Option<Secret<String>>,
pub zip: Option<Secret<String>>,
}
diff --git a/crates/router/src/connector/worldpay/requests.rs b/crates/router/src/connector/worldpay/requests.rs
index 5d6fdeb5106..5fb5d75d940 100644
--- a/crates/router/src/connector/worldpay/requests.rs
+++ b/crates/router/src/connector/worldpay/requests.rs
@@ -6,15 +6,15 @@ pub struct BillingAddress {
#[serde(skip_serializing_if = "Option::is_none")]
pub city: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
- pub address2: Option<String>,
- pub postal_code: String,
+ pub address2: Option<Secret<String>>,
+ pub postal_code: Secret<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub state: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
- pub address3: Option<String>,
- pub country_code: String,
+ pub address3: Option<Secret<String>>,
+ pub country_code: common_enums::CountryAlpha2,
#[serde(skip_serializing_if = "Option::is_none")]
- pub address1: Option<String>,
+ pub address1: Option<Secret<String>>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
@@ -57,7 +57,7 @@ pub enum CustomerAuthentication {
#[serde(rename_all = "camelCase")]
pub struct ThreeDS {
#[serde(skip_serializing_if = "Option::is_none")]
- pub authentication_value: Option<String>,
+ pub authentication_value: Option<Secret<String>>,
pub version: ThreeDSVersion,
#[serde(skip_serializing_if = "Option::is_none")]
pub transaction_id: Option<String>,
@@ -93,7 +93,7 @@ pub enum CustomerAuthType {
pub struct NetworkToken {
#[serde(rename = "type")]
pub auth_type: CustomerAuthType,
- pub authentication_value: String,
+ pub authentication_value: Secret<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub eci: Option<String>,
}
@@ -146,7 +146,7 @@ pub struct CardPayment {
#[serde(skip_serializing_if = "Option::is_none")]
pub billing_address: Option<BillingAddress>,
#[serde(skip_serializing_if = "Option::is_none")]
- pub card_holder_name: Option<String>,
+ pub card_holder_name: Option<Secret<String>>,
pub card_expiry_date: CardExpiryDate,
#[serde(skip_serializing_if = "Option::is_none")]
pub cvc: Option<Secret<String>>,
@@ -168,15 +168,15 @@ pub struct CardToken {
pub struct WalletPayment {
#[serde(rename = "type")]
pub payment_type: PaymentType,
- pub wallet_token: String,
+ pub wallet_token: Secret<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub billing_address: Option<BillingAddress>,
}
#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
pub struct CardExpiryDate {
- pub month: i8,
- pub year: i32,
+ pub month: Secret<i8>,
+ pub year: Secret<i32>,
}
#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
@@ -198,9 +198,9 @@ pub struct Merchant {
#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentFacilitator {
- pub pf_id: String,
+ pub pf_id: Secret<String>,
#[serde(skip_serializing_if = "Option::is_none")]
- pub iso_id: Option<String>,
+ pub iso_id: Option<Secret<String>>,
pub sub_merchant: SubMerchant,
}
@@ -208,13 +208,13 @@ pub struct PaymentFacilitator {
#[serde(rename_all = "camelCase")]
pub struct SubMerchant {
pub city: String,
- pub name: String,
+ pub name: Secret<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub state: Option<String>,
- pub postal_code: String,
- pub merchant_id: String,
+ pub postal_code: Secret<String>,
+ pub merchant_id: Secret<String>,
pub country_code: String,
- pub street: String,
+ pub street: Secret<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub tax_id: Option<String>,
}
diff --git a/crates/router/src/connector/worldpay/response.rs b/crates/router/src/connector/worldpay/response.rs
index e51b716acf6..0a50885d28e 100644
--- a/crates/router/src/connector/worldpay/response.rs
+++ b/crates/router/src/connector/worldpay/response.rs
@@ -1,3 +1,4 @@
+use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::{core::errors, types};
@@ -124,12 +125,14 @@ impl Exemption {
#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Issuer {
- pub authorization_code: String,
+ pub authorization_code: Secret<String>,
}
impl Issuer {
- pub fn new(authorization_code: String) -> Self {
- Self { authorization_code }
+ pub fn new(code: String) -> Self {
+ Self {
+ authorization_code: Secret::new(code),
+ }
}
}
@@ -187,9 +190,9 @@ impl PaymentInstrumentCard {
#[serde(rename_all = "camelCase")]
pub struct PaymentInstrumentCardExpiryDate {
#[serde(skip_serializing_if = "Option::is_none")]
- pub month: Option<i32>,
+ pub month: Option<Secret<i32>>,
#[serde(skip_serializing_if = "Option::is_none")]
- pub year: Option<i32>,
+ pub year: Option<Secret<i32>>,
}
impl PaymentInstrumentCardExpiryDate {
diff --git a/crates/router/src/connector/worldpay/transformers.rs b/crates/router/src/connector/worldpay/transformers.rs
index 6979502842f..dd92984eb99 100644
--- a/crates/router/src/connector/worldpay/transformers.rs
+++ b/crates/router/src/connector/worldpay/transformers.rs
@@ -1,7 +1,6 @@
use base64::Engine;
use common_utils::errors::CustomResult;
use diesel_models::enums;
-use error_stack::{IntoReport, ResultExt};
use masking::{PeekInterface, Secret};
use serde::Serialize;
@@ -47,20 +46,8 @@ fn fetch_payment_instrument(
match payment_method {
api::PaymentMethodData::Card(card) => Ok(PaymentInstrument::Card(CardPayment {
card_expiry_date: CardExpiryDate {
- month: card
- .card_exp_month
- .peek()
- .clone()
- .parse::<i8>()
- .into_report()
- .change_context(errors::ConnectorError::ResponseDeserializationFailed)?,
- year: card
- .card_exp_year
- .peek()
- .clone()
- .parse::<i32>()
- .into_report()
- .change_context(errors::ConnectorError::ResponseDeserializationFailed)?,
+ month: utils::CardData::get_expiry_month_as_i8(&card)?,
+ year: utils::CardData::get_expiry_year_as_i32(&card)?,
},
card_number: card.card_number,
..CardPayment::default()
@@ -69,14 +56,14 @@ fn fetch_payment_instrument(
api_models::payments::WalletData::GooglePay(data) => {
Ok(PaymentInstrument::Googlepay(WalletPayment {
payment_type: PaymentType::Googlepay,
- wallet_token: data.tokenization_data.token,
+ wallet_token: Secret::new(data.tokenization_data.token),
..WalletPayment::default()
}))
}
api_models::payments::WalletData::ApplePay(data) => {
Ok(PaymentInstrument::Applepay(WalletPayment {
payment_type: PaymentType::Applepay,
- wallet_token: data.payment_data,
+ wallet_token: Secret::new(data.payment_data),
..WalletPayment::default()
}))
}
diff --git a/crates/router/src/connector/zen/transformers.rs b/crates/router/src/connector/zen/transformers.rs
index ebea61304a1..b01b3f027a0 100644
--- a/crates/router/src/connector/zen/transformers.rs
+++ b/crates/router/src/connector/zen/transformers.rs
@@ -2,7 +2,7 @@ use api_models::payments::Card;
use cards::CardNumber;
use common_utils::{ext_traits::ValueExt, pii};
use error_stack::ResultExt;
-use masking::{PeekInterface, Secret};
+use masking::{ExposeInterface, PeekInterface, Secret};
use ring::digest;
use serde::{Deserialize, Serialize};
use strum::Display;
@@ -200,8 +200,8 @@ pub struct SessionObject {
#[derive(Debug, Serialize, Deserialize)]
pub struct WalletSessionData {
- pub terminal_uuid: Option<String>,
- pub pay_wall_secret: Option<String>,
+ pub terminal_uuid: Option<Secret<String>>,
+ pub pay_wall_secret: Option<Secret<String>>,
}
impl TryFrom<(&ZenRouterData<&types::PaymentsAuthorizeRouterData>, &Card)> for ZenPaymentsRequest {
@@ -513,7 +513,8 @@ impl
let terminal_uuid = session_data
.terminal_uuid
.clone()
- .ok_or(errors::ConnectorError::RequestEncodingFailed)?;
+ .ok_or(errors::ConnectorError::RequestEncodingFailed)?
+ .expose();
let mut checkout_request = CheckoutRequest {
merchant_transaction_id: item.router_data.connector_request_reference_id.clone(),
specified_payment_channel,
@@ -540,7 +541,7 @@ fn get_checkout_signature(
.clone()
.ok_or(errors::ConnectorError::RequestEncodingFailed)?;
let mut signature_data = get_signature_data(checkout_request)?;
- signature_data.push_str(&pay_wall_secret);
+ signature_data.push_str(&pay_wall_secret.expose());
let payload_digest = digest::digest(&digest::SHA256, signature_data.as_bytes());
let mut signature = hex::encode(payload_digest);
signature.push_str(";sha256");
|
2024-03-04T09:40:32Z
|
## 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 -->
Mask pii information passed and received in the connector request and response for Worldline, Worldpay and zen.
## Test Case
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
_Note: Zen Googlepay and Worldpay can't be tested in sandbox_
1. Create a card payment with worldpay
2. Check if all the sensitive data in the `masked_response` is masked
```
curl --location '{{base_url}}/analytics/v1/connector_event_logs?type=Payment&payment_id={{payment_id}}' \
--header 'sec-ch-ua: "Not A(Brand";v="99", "Google Chrome";v="121", "Chromium";v="121"' \
--header 'sec-ch-ua-mobile: ?0' \
--header 'authorization: Bearer JWT_token' \
--header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36' \
--header 'Content-Type: application/json' \
--header 'Referer: https://integ.hyperswitch.io/' \
--header 'api-key: {{api-key}}' \
--header 'sec-ch-ua-platform: "macOS"'
```
Response
```
request\":\"{\\\"cardPaymentMethodSpecificInput\\\":{\\\"card\\\":{\\\"cardNumber\\\":\\\"456735**********\\\",\\\"cardholderName\\\":\\\"*** alloc::string::String ***\\\",\\\"cvv\\\":\\\"*** alloc::string::String ***\\\",\\\"expiryDate\\\":\\\"*** alloc::string::String ***\\\"},\\\"requiresApproval\\\":false,\\\"paymentProductId\\\":1},\\\"order\\\":{\\\"amountOfMoney\\\":{\\\"amount\\\":20000,\\\"currencyCode\\\":\\\"PLN\\\"},\\\"customer\\\":{\\\"billingAddress\\\":{\\\"city\\\":\\\"San Fransico\\\",\\\"countryCode\\\":\\\"US\\\",\\\"houseNumber\\\":null,\\\"state\\\":\\\"*** alloc::string::String ***\\\",\\\"stateCode\\\":null,\\\"street\\\":null,\\\"zip\\\":\\\"*** alloc::string::String ***\\\"},\\\"contactDetails\\\":{\\\"emailAddress\\\":\\\"*********@gmail.com\\\",\\\"mobilePhoneNumber\\\":null}},\\\"references\\\":{\\\"merchantReference\\\":\\\"pay_Cm4XoGAkTeXdAaAx3OUo_1\\\"}},\\\"shipping\\\":{\\\"city\\\":\\\"San Fransico\\\",\\\"countryCode\\\":\\\"US\\\",\\\"houseNumber\\\":null,\\\"name\\\":{\\\"firstName\\\":\\\"*** alloc::string::String ***\\\",\\\"surname\\\":\\\"*** alloc::string::String ***\\\",\\\"surnamePrefix\\\":null,\\\"title\\\":null},\\\"state\\\":\\\"*** alloc::string::String ***\\\",\\\"stateCode\\\":null,\\\"street\\\":null,\\\"zip\\\":\\\"*** alloc::string::String ***\\\"}}\",\"masked_response\":\"{\\\"payment\\\":{\\\"id\\\":\\\"000000113200000139460000100001\\\",\\\"status\\\":\\\"CAPTURE_REQUESTED\\\",\\\"capture_method\\\":\\\"automatic\\\"},
```
## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
ac8ddd40208f3da5f65ca97bf5033cea5ca3ebe3
|
|
juspay/hyperswitch
|
juspay__hyperswitch-3950
|
Bug: [REFACTOR] handle payment method duplication in payouts
Currently, when same payment method is saved in payouts, duplication logic is not handled.
Locker returns `duplication_check` based on which duplication of payment methods has to be handled in Hyperswitch.
This issue similar to https://github.com/juspay/hyperswitch/issues/3147
|
diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs
index f639aa59218..357f077332d 100644
--- a/crates/router/src/core/payment_methods/transformers.rs
+++ b/crates/router/src/core/payment_methods/transformers.rs
@@ -27,6 +27,15 @@ pub enum StoreLockerReq<'a> {
LockerGeneric(StoreGenericReq<'a>),
}
+impl StoreLockerReq<'_> {
+ pub fn update_requestor_card_reference(&mut self, card_reference: Option<String>) {
+ match self {
+ Self::LockerCard(c) => c.requestor_card_reference = card_reference,
+ Self::LockerGeneric(_) => (),
+ }
+ }
+}
+
#[derive(Debug, Deserialize, Serialize)]
pub struct StoreCardReq<'a> {
pub merchant_id: &'a str,
diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rs
index 566caa7acc5..04c80cc6267 100644
--- a/crates/router/src/core/payouts.rs
+++ b/crates/router/src/core/payouts.rs
@@ -1337,7 +1337,10 @@ pub async fn fulfill_payout(
.status
.unwrap_or(payout_attempt.status.to_owned());
payout_data.payouts.status = status;
- if payout_data.payouts.recurring && payout_data.payouts.payout_method_id.is_none() {
+ if payout_data.payouts.recurring
+ && payout_data.payouts.payout_method_id.is_none()
+ && !helpers::is_payout_err_state(status)
+ {
helpers::save_payout_data_to_locker(
state,
payout_data,
diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs
index 6efe6ee9a77..5681999ae9f 100644
--- a/crates/router/src/core/payouts/helpers.rs
+++ b/crates/router/src/core/payouts/helpers.rs
@@ -1,4 +1,4 @@
-use api_models::enums::PayoutConnectors;
+use api_models::{enums, payouts};
use common_utils::{
errors::CustomResult,
ext_traits::{AsyncExt, StringExt},
@@ -11,10 +11,12 @@ use router_env::logger;
use super::PayoutData;
use crate::{
core::{
- errors::{self, RouterResult},
+ errors::{self, RouterResult, StorageErrorExt},
payment_methods::{
cards,
- transformers::{self, StoreCardReq, StoreGenericReq, StoreLockerReq},
+ transformers::{
+ self, DataDuplicationCheck, StoreCardReq, StoreGenericReq, StoreLockerReq,
+ },
vault,
},
payments::{
@@ -191,9 +193,9 @@ pub async fn save_payout_data_to_locker(
key_store: &domain::MerchantKeyStore,
) -> RouterResult<()> {
let payout_attempt = &payout_data.payout_attempt;
- let (locker_req, card_details, bank_details, wallet_details, payment_method_type) =
+ let (mut locker_req, card_details, bank_details, wallet_details, payment_method_type) =
match payout_method_data {
- api_models::payouts::PayoutMethodData::Card(card) => {
+ payouts::PayoutMethodData::Card(card) => {
let card_detail = api::CardDetail {
card_number: card.card_number.to_owned(),
card_holder_name: card.card_holder_name.to_owned(),
@@ -206,7 +208,7 @@ pub async fn save_payout_data_to_locker(
card_type: None,
};
let payload = StoreLockerReq::LockerCard(StoreCardReq {
- merchant_id: &merchant_account.merchant_id,
+ merchant_id: merchant_account.merchant_id.as_ref(),
merchant_customer_id: payout_attempt.customer_id.to_owned(),
card: transformers::Card {
card_number: card.card_number.to_owned(),
@@ -250,31 +252,32 @@ pub async fn save_payout_data_to_locker(
Ok(hex::encode(e.peek()))
})?;
let payload = StoreLockerReq::LockerGeneric(StoreGenericReq {
- merchant_id: &merchant_account.merchant_id,
+ merchant_id: merchant_account.merchant_id.as_ref(),
merchant_customer_id: payout_attempt.customer_id.to_owned(),
enc_data,
});
match payout_method_data {
- api_models::payouts::PayoutMethodData::Bank(bank) => (
+ payouts::PayoutMethodData::Bank(bank) => (
payload,
None,
Some(bank.to_owned()),
None,
api_enums::PaymentMethodType::foreign_from(bank.to_owned()),
),
- api_models::payouts::PayoutMethodData::Wallet(wallet) => (
+ payouts::PayoutMethodData::Wallet(wallet) => (
payload,
None,
None,
Some(wallet.to_owned()),
api_enums::PaymentMethodType::foreign_from(wallet.to_owned()),
),
- api_models::payouts::PayoutMethodData::Card(_) => {
+ payouts::PayoutMethodData::Card(_) => {
Err(errors::ApiErrorResponse::InternalServerError)?
}
}
}
};
+
// Store payout method in locker
let stored_resp = cards::call_to_locker_hs(
state,
@@ -285,113 +288,272 @@ pub async fn save_payout_data_to_locker(
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
- // Store card_reference in payouts table
let db = &*state.store;
- let updated_payout = storage::PayoutsUpdate::PayoutMethodIdUpdate {
- payout_method_id: Some(stored_resp.card_reference.to_owned()),
+
+ // Handle duplicates
+ let (should_insert_in_pm_table, metadata_update) = match stored_resp.duplication_check {
+ // Check if equivalent entry exists in payment_methods
+ Some(duplication_check) => {
+ let locker_ref = stored_resp.card_reference.clone();
+
+ // Use locker ref as payment_method_id
+ let existing_pm_by_pmid = db.find_payment_method(&locker_ref).await;
+
+ match existing_pm_by_pmid {
+ // If found, update locker's metadata [DELETE + INSERT OP], don't insert in payment_method's table
+ Ok(pm) => (
+ false,
+ if duplication_check == DataDuplicationCheck::MetaDataChanged {
+ Some(pm.clone())
+ } else {
+ None
+ },
+ ),
+
+ // If not found, use locker ref as locker_id
+ Err(err) => {
+ if err.current_context().is_db_not_found() {
+ match db.find_payment_method_by_locker_id(&locker_ref).await {
+ // If found, update locker's metadata [DELETE + INSERT OP], don't insert in payment_methods table
+ Ok(pm) => (
+ false,
+ if duplication_check == DataDuplicationCheck::MetaDataChanged {
+ Some(pm.clone())
+ } else {
+ None
+ },
+ ),
+ Err(err) => {
+ // If not found, update locker's metadata [DELETE + INSERT OP], and insert in payment_methods table
+ if err.current_context().is_db_not_found() {
+ (true, None)
+
+ // Misc. DB errors
+ } else {
+ Err(err)
+ .change_context(
+ errors::ApiErrorResponse::InternalServerError,
+ )
+ .attach_printable(
+ "DB failures while finding payment method by locker ID",
+ )?
+ }
+ }
+ }
+ // Misc. DB errors
+ } else {
+ Err(err)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("DB failures while finding payment method by pm ID")?
+ }
+ }
+ }
+ }
+
+ // Not duplicate, should be inserted in payment_methods table
+ None => (true, None),
};
- db.update_payout(
- &payout_data.payouts,
- updated_payout,
- merchant_account.storage_scheme,
- )
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Error updating payouts in saved payout method")?;
- // fetch card info from db
- let card_isin = card_details
- .as_ref()
- .map(|c| c.card_number.clone().get_card_isin());
+ // Form payment method entry and card's metadata whenever insertion or metadata update is required
+ let (card_details_encrypted, new_payment_method) =
+ if let (api::PayoutMethodData::Card(_), true, _)
+ | (api::PayoutMethodData::Card(_), _, Some(_)) = (
+ payout_method_data,
+ should_insert_in_pm_table,
+ 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 mut payment_method = api::PaymentMethodCreate {
+ payment_method: api_enums::PaymentMethod::foreign_from(
+ payout_method_data.to_owned(),
+ ),
+ payment_method_type: Some(payment_method_type),
+ payment_method_issuer: None,
+ payment_method_issuer_code: None,
+ bank_transfer: None,
+ card: card_details.clone(),
+ wallet: None,
+ metadata: None,
+ customer_id: Some(payout_attempt.customer_id.to_owned()),
+ card_network: None,
+ };
- let pm_data = card_isin
- .clone()
- .async_and_then(|card_isin| async move {
- db.get_card_info(&card_isin)
+ let pm_data = card_isin
+ .clone()
+ .async_and_then(|card_isin| async move {
+ db.get_card_info(&card_isin)
+ .await
+ .map_err(|error| services::logger::warn!(card_info_error=?error))
+ .ok()
+ })
.await
- .map_err(|error| services::logger::warn!(card_info_error=?error))
- .ok()
- })
- .await
- .flatten()
- .map(|card_info| {
- api::payment_methods::PaymentMethodsData::Card(
- api::payment_methods::CardDetailsPaymentMethod {
- last4_digits: card_details
- .as_ref()
- .map(|c| c.card_number.clone().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()),
- nick_name: card_details.as_ref().and_then(|c| c.nick_name.clone()),
- card_holder_name: card_details
- .as_ref()
- .and_then(|c| c.card_holder_name.clone()),
-
- card_isin: card_isin.clone(),
- card_issuer: card_info.card_issuer,
- card_network: card_info.card_network,
- card_type: card_info.card_type,
- saved_to_locker: true,
- },
+ .flatten()
+ .map(|card_info| {
+ payment_method.payment_method_issuer = card_info.card_issuer.clone();
+ payment_method.card_network =
+ 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()),
+ 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()),
+ nick_name: card_details.as_ref().and_then(|c| c.nick_name.clone()),
+ card_holder_name: card_details
+ .as_ref()
+ .and_then(|c| c.card_holder_name.clone()),
+
+ card_isin: card_isin.clone(),
+ card_issuer: card_info.card_issuer,
+ card_network: card_info.card_network,
+ card_type: card_info.card_type,
+ saved_to_locker: true,
+ },
+ )
+ })
+ .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()),
+ 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()),
+ nick_name: card_details.as_ref().and_then(|c| c.nick_name.clone()),
+ card_holder_name: card_details
+ .as_ref()
+ .and_then(|c| c.card_holder_name.clone()),
+
+ card_isin: card_isin.clone(),
+ card_issuer: None,
+ card_network: None,
+ card_type: None,
+ saved_to_locker: true,
+ },
+ )
+ });
+ (
+ cards::create_encrypted_payment_method_data(key_store, Some(pm_data)).await,
+ payment_method,
)
- })
- .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()),
- 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()),
- nick_name: card_details.as_ref().and_then(|c| c.nick_name.clone()),
- card_holder_name: card_details
- .as_ref()
- .and_then(|c| c.card_holder_name.clone()),
-
- card_isin: card_isin.clone(),
- card_issuer: None,
+ } else {
+ (
+ None,
+ api::PaymentMethodCreate {
+ payment_method: api_enums::PaymentMethod::foreign_from(
+ payout_method_data.to_owned(),
+ ),
+ payment_method_type: Some(payment_method_type),
+ payment_method_issuer: None,
+ payment_method_issuer_code: None,
+ bank_transfer: bank_details,
+ card: None,
+ wallet: wallet_details,
+ metadata: None,
+ customer_id: Some(payout_attempt.customer_id.to_owned()),
card_network: None,
- card_type: None,
- saved_to_locker: true,
},
)
- });
-
- let card_details_encrypted =
- cards::create_encrypted_payment_method_data(key_store, Some(pm_data)).await;
-
- // Insert in payment_method table
- let payment_method = api::PaymentMethodCreate {
- payment_method: api_enums::PaymentMethod::foreign_from(payout_method_data.to_owned()),
- payment_method_type: Some(payment_method_type),
- payment_method_issuer: None,
- payment_method_issuer_code: None,
- bank_transfer: bank_details,
- card: card_details,
- wallet: wallet_details,
- metadata: None,
- customer_id: Some(payout_attempt.customer_id.to_owned()),
- card_network: None,
+ };
+
+ // Insert new entry in payment_methods table
+ if should_insert_in_pm_table {
+ let payment_method_id = common_utils::generate_id(crate::consts::ID_LENGTH, "pm");
+ cards::create_payment_method(
+ db,
+ &new_payment_method,
+ &payout_attempt.customer_id,
+ &payment_method_id,
+ Some(stored_resp.card_reference.clone()),
+ &merchant_account.merchant_id,
+ None,
+ None,
+ card_details_encrypted.clone(),
+ key_store,
+ None,
+ None,
+ )
+ .await?;
+ }
+
+ /* 1. Delete from locker
+ * 2. Create new entry in locker
+ * 3. Handle creation response from locker
+ * 4. Update card's metadata in payment_methods table
+ */
+ if let Some(existing_pm) = metadata_update {
+ let card_reference = &existing_pm
+ .locker_id
+ .clone()
+ .unwrap_or(existing_pm.payment_method_id.clone());
+ // Delete from locker
+ cards::delete_card_from_hs_locker(
+ state,
+ &payout_attempt.customer_id,
+ &merchant_account.merchant_id,
+ card_reference,
+ )
+ .await
+ .attach_printable(
+ "Failed to delete PMD from locker as a part of metadata update operation",
+ )?;
+
+ locker_req.update_requestor_card_reference(Some(card_reference.to_string()));
+
+ // Store in locker
+ let stored_resp = cards::call_to_locker_hs(
+ state,
+ &locker_req,
+ &payout_attempt.customer_id,
+ api_enums::LockerChoice::HyperswitchCardVault,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError);
+
+ // Check if locker operation was successful or not, if not, delete the entry from payment_methods table
+ if let Err(err) = stored_resp {
+ logger::error!(vault_err=?err);
+ db.delete_payment_method_by_merchant_id_payment_method_id(
+ &merchant_account.merchant_id,
+ &existing_pm.payment_method_id,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
+
+ Err(errors::ApiErrorResponse::InternalServerError).attach_printable(
+ "Failed to insert PMD from locker as a part of metadata update operation",
+ )?
+ };
+
+ // Update card's metadata in payment_methods table
+ let pm_update = storage::PaymentMethodUpdate::PaymentMethodDataUpdate {
+ payment_method_data: card_details_encrypted,
+ };
+ db.update_payment_method(existing_pm, pm_update)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to add payment method in db")?;
};
- let payment_method_id = common_utils::generate_id(crate::consts::ID_LENGTH, "pm");
- cards::create_payment_method(
- db,
- &payment_method,
- &payout_attempt.customer_id,
- &payment_method_id,
- Some(stored_resp.card_reference),
- &merchant_account.merchant_id,
- None,
- None,
- card_details_encrypted,
- key_store,
- None,
- None,
+ // Store card_reference in payouts table
+ let updated_payout = storage::PayoutsUpdate::PayoutMethodIdUpdate {
+ payout_method_id: Some(stored_resp.card_reference.to_owned()),
+ };
+ db.update_payout(
+ &payout_data.payouts,
+ updated_payout,
+ merchant_account.storage_scheme,
)
- .await?;
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Error updating payouts in saved payout method")?;
Ok(())
}
@@ -626,7 +788,7 @@ pub fn should_call_payout_connector_create_customer<'a>(
connector_label: &str,
) -> (bool, Option<&'a str>) {
// Check if create customer is required for the connector
- match PayoutConnectors::try_from(connector.connector_name) {
+ match enums::PayoutConnectors::try_from(connector.connector_name) {
Ok(connector) => {
let connector_needs_customer = state
.conf
|
2024-03-07T16:47:54Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
Explained in #3950
### 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?
_**Note -** DM for postman collection_

For ensuring card duplication is handled in payouts flow, we use below procedure (assuming merchant accounts and connector accounts are created)
- Create a new customer
- Save a card for this customer using /payment_methods endpoint
- Create a new payout for this customer using the same card number
- Payouts flow would try to persist these details in locker
- **Test # 1** - listing customer's PMs should return a single PM
- Create a new payout using SPM
- Payout flow would try to persist these details again
- **Test # 2** - listing customer's PMs should return a single PM
- Try to save the same card details for this user using /payment_methods again
- **Test # 3** - listing customer's PMs should return a single PM
Above test cases are present in postman collection.
## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
21e2d78117a9e25708b8c6a2280f6a836ee86072
|
|
juspay/hyperswitch
|
juspay__hyperswitch-3931
|
Bug: [FEATURE] :[Prophetpay][Rapyd][Shift4][Square] mask pii information in connector request and response
### Feature Description
Mask pii information passed and received in the connector request and response
### Possible Implementation
Refactor all sensitive response and request fields into a secret
### 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/prophetpay/transformers.rs b/crates/router/src/connector/prophetpay/transformers.rs
index b3b641b6d24..563438203d8 100644
--- a/crates/router/src/connector/prophetpay/transformers.rs
+++ b/crates/router/src/connector/prophetpay/transformers.rs
@@ -2,7 +2,7 @@ use std::collections::HashMap;
use common_utils::{consts, errors::CustomResult};
use error_stack::{IntoReport, ResultExt};
-use masking::{PeekInterface, Secret};
+use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use url::Url;
@@ -172,7 +172,7 @@ impl TryFrom<&ProphetpayRouterData<&types::PaymentsAuthorizeRouterData>>
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ProphetpayTokenResponse {
- hosted_tokenize_id: String,
+ hosted_tokenize_id: Secret<String>,
}
impl<F>
@@ -197,7 +197,7 @@ impl<F>
let url_data = format!(
"{}{}",
consts::PROPHETPAY_REDIRECT_URL,
- item.response.hosted_tokenize_id
+ item.response.hosted_tokenize_id.expose()
);
let redirect_url = Url::parse(url_data.as_str())
@@ -257,7 +257,7 @@ pub struct ProphetpayCompleteRequest {
inquiry_reference: String,
profile: Secret<String>,
action_type: i8,
- card_token: String,
+ card_token: Secret<String>,
}
impl TryFrom<&ProphetpayRouterData<&types::PaymentsCompleteAuthorizeRouterData>>
@@ -268,7 +268,9 @@ impl TryFrom<&ProphetpayRouterData<&types::PaymentsCompleteAuthorizeRouterData>>
item: &ProphetpayRouterData<&types::PaymentsCompleteAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let auth_data = ProphetpayAuthType::try_from(&item.router_data.connector_auth_type)?;
- let card_token = get_card_token(item.router_data.request.redirect_response.clone())?;
+ let card_token = Secret::new(get_card_token(
+ item.router_data.request.redirect_response.clone(),
+ )?);
Ok(Self {
amount: item.amount.to_owned(),
ref_info: item.router_data.connector_request_reference_id.to_owned(),
diff --git a/crates/router/src/connector/rapyd/transformers.rs b/crates/router/src/connector/rapyd/transformers.rs
index 9fd664748e3..bd50a95d8b9 100644
--- a/crates/router/src/connector/rapyd/transformers.rs
+++ b/crates/router/src/connector/rapyd/transformers.rs
@@ -87,7 +87,7 @@ pub struct Address {
city: Option<String>,
state: Option<Secret<String>>,
country: Option<String>,
- zip: Option<String>,
+ zip: Option<Secret<String>>,
phone_number: Option<Secret<String>>,
}
@@ -96,7 +96,7 @@ pub struct RapydWallet {
#[serde(rename = "type")]
payment_type: String,
#[serde(rename = "details")]
- token: Option<String>,
+ token: Option<Secret<String>>,
}
impl TryFrom<&RapydRouterData<&types::PaymentsAuthorizeRouterData>> for RapydPaymentsRequest {
@@ -145,11 +145,11 @@ impl TryFrom<&RapydRouterData<&types::PaymentsAuthorizeRouterData>> for RapydPay
let digital_wallet = match wallet_data {
api_models::payments::WalletData::GooglePay(data) => Some(RapydWallet {
payment_type: "google_pay".to_string(),
- token: Some(data.tokenization_data.token.to_owned()),
+ token: Some(Secret::new(data.tokenization_data.token.to_owned())),
}),
api_models::payments::WalletData::ApplePay(data) => Some(RapydWallet {
payment_type: "apple_pay".to_string(),
- token: Some(data.payment_data.to_string()),
+ token: Some(Secret::new(data.payment_data.to_string())),
}),
_ => None,
};
@@ -418,7 +418,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>>
#[derive(Debug, Serialize, Clone)]
pub struct CaptureRequest {
amount: Option<i64>,
- receipt_email: Option<String>,
+ receipt_email: Option<Secret<String>>,
statement_descriptor: Option<String>,
}
diff --git a/crates/router/src/connector/shift4/transformers.rs b/crates/router/src/connector/shift4/transformers.rs
index 97c19c49af8..4dc2cd2cd09 100644
--- a/crates/router/src/connector/shift4/transformers.rs
+++ b/crates/router/src/connector/shift4/transformers.rs
@@ -117,7 +117,7 @@ pub struct Card {
#[serde(untagged)]
pub enum CardPayment {
RawCard(Box<Card>),
- CardToken(String),
+ CardToken(Secret<String>),
}
impl<T> TryFrom<&types::RouterData<T, types::PaymentsAuthorizeData, types::PaymentsResponseData>>
@@ -577,7 +577,7 @@ pub struct Shift4ThreeDsResponse {
#[derive(Default, Debug, Deserialize, Serialize)]
pub struct Token {
- pub id: String,
+ pub id: Secret<String>,
pub created: i64,
#[serde(rename = "objectType")]
pub object_type: String,
@@ -629,7 +629,7 @@ pub enum NextAction {
#[derive(Debug, Serialize, Deserialize)]
pub struct Shift4CardToken {
- pub id: String,
+ pub id: Secret<String>,
}
impl<F>
diff --git a/crates/router/src/connector/square/transformers.rs b/crates/router/src/connector/square/transformers.rs
index 1e5501575ad..03bd0ac83ee 100644
--- a/crates/router/src/connector/square/transformers.rs
+++ b/crates/router/src/connector/square/transformers.rs
@@ -181,7 +181,7 @@ impl TryFrom<&types::TokenizationRouterData> for SquareTokenRequest {
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SquareSessionResponse {
- session_id: String,
+ session_id: Secret<String>,
}
impl<F, T>
@@ -194,9 +194,9 @@ impl<F, T>
) -> Result<Self, Self::Error> {
Ok(Self {
status: storage::enums::AttemptStatus::Pending,
- session_token: Some(item.response.session_id.clone()),
+ session_token: Some(item.response.session_id.clone().expose()),
response: Ok(types::PaymentsResponseData::SessionTokenResponse {
- session_token: item.response.session_id,
+ session_token: item.response.session_id.expose(),
}),
..item.data
})
|
2024-03-04T07:08:32Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [x] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Mask pii information passed and received in the connector request and response for Prophetpay, rapyd, shift4 and square.
## Test Case
<!--
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 card redirect payment with Prophetpay
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key:{{api_key}}' \
--data '{
"amount": 8000,
"currency": "USD",
"confirm": true,
"amount_to_capture": 8000,
"business_country": "US",
"customer_id": "custhype1232",
"return_url": "https://www.google.com",
"payment_method": "card_redirect",
"payment_method_type": "card_redirect",
"payment_method_data": {
"card_redirect": {
"card_redirect": {}
}
},
"routing": {
"type": "single",
"data": "prophetpay"
}
}'
```
2.Rapyd Applepay
3.Create a 3DS payment with Shift4
_Note: Currently there is a known bug in this flow. We get an `Unable to parse request - unrecognized field: card[number]` error_
4.Square card payment there is a known bug - #3974
5. Check if all the sensitive data in the `masked_response` is masked
```
curl --location '{{base_url}}/analytics/v1/connector_event_logs?type=Payment&payment_id={{payment_id}}' \
--header 'sec-ch-ua: "Not A(Brand";v="99", "Google Chrome";v="121", "Chromium";v="121"' \
--header 'sec-ch-ua-mobile: ?0' \
--header 'authorization: Bearer JWT_token' \
--header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36' \
--header 'Content-Type: application/json' \
--header 'Referer: https://integ.hyperswitch.io/' \
--header 'api-key: {{api-key}}' \
--header 'sec-ch-ua-platform: "macOS"'
```
1. Prophetpay Response
```
\"masked_response\":\"{\\\"hostedTokenizeId\\\":\\\"*** alloc::string::String ***\\\"}\
```
```
request\":\"{\\\"amount\\\":80.0,\\\"refInfo\\\":\\\"pay_MBu0Wfts32TfURFTNJJn_1\\\",\\\"inquiryReference\\\":\\\"pay_MBu0Wfts32TfURFTNJJn_1\\\",\\\"profile\\\":\\\"*** alloc::string::String ***\\\",\\\"actionType\\\":1,\\\"cardToken\\\":\\\"*** alloc::string::String ***\\\"}\",\"masked_response\":\"{\\\"success\\\":true,\\\"responseText\\\":\\\"Success\\\",\\\"transactionID\\\":\\\"2237854484\\\",\\\"responseCode\\\":\\\"0\\\"}
```
## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
5bb67c7dcc22f9cee51adf501bdd8455b41548db
|
|
juspay/hyperswitch
|
juspay__hyperswitch-3929
|
Bug: [FEATURE] : [Paypal][Payu][Placetopay][PowerTranz] mask pii information in connector request and response
### Feature Description
Mask pii information passed and received in the connector request and response
### Possible Implementation
Refactor all sensitive response and request fields secret
### 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/payu/transformers.rs b/crates/router/src/connector/payu/transformers.rs
index e3ad6f8b426..e8699a1a0ed 100644
--- a/crates/router/src/connector/payu/transformers.rs
+++ b/crates/router/src/connector/payu/transformers.rs
@@ -1,4 +1,5 @@
use base64::Engine;
+use common_utils::pii::{Email, IpAddress};
use error_stack::{IntoReport, ResultExt};
use serde::{Deserialize, Serialize};
@@ -15,7 +16,7 @@ const WALLET_IDENTIFIER: &str = "PBL";
#[derive(Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct PayuPaymentsRequest {
- customer_ip: std::net::IpAddr,
+ customer_ip: Secret<String, IpAddress>,
merchant_pos_id: Secret<String>,
total_amount: i64,
currency_code: enums::Currency,
@@ -55,7 +56,7 @@ pub struct PayuWallet {
pub value: PayuWalletCode,
#[serde(rename = "type")]
pub wallet_type: String,
- pub authorization_code: String,
+ pub authorization_code: Secret<String>,
}
#[derive(Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "lowercase")]
@@ -83,8 +84,9 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PayuPaymentsRequest {
PayuWallet {
value: PayuWalletCode::Ap,
wallet_type: WALLET_IDENTIFIER.to_string(),
- authorization_code: consts::BASE64_ENGINE
- .encode(data.tokenization_data.token),
+ authorization_code: Secret::new(
+ consts::BASE64_ENGINE.encode(data.tokenization_data.token),
+ ),
}
}),
}),
@@ -93,7 +95,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PayuPaymentsRequest {
PayuWallet {
value: PayuWalletCode::Jp,
wallet_type: WALLET_IDENTIFIER.to_string(),
- authorization_code: data.payment_data,
+ authorization_code: Secret::new(data.payment_data),
}
}),
}),
@@ -111,11 +113,14 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PayuPaymentsRequest {
},
)?;
Ok(Self {
- customer_ip: browser_info.ip_address.ok_or(
- errors::ConnectorError::MissingRequiredField {
- field_name: "browser_info.ip_address",
- },
- )?,
+ customer_ip: Secret::new(
+ browser_info
+ .ip_address
+ .ok_or(errors::ConnectorError::MissingRequiredField {
+ field_name: "browser_info.ip_address",
+ })?
+ .to_string(),
+ ),
merchant_pos_id: auth_type.merchant_pos_id,
total_amount: item.request.amount,
currency_code: item.request.currency,
@@ -401,8 +406,8 @@ pub struct PayuOrderResponseData {
ext_order_id: Option<String>,
order_create_date: String,
notify_url: Option<String>,
- customer_ip: std::net::IpAddr,
- merchant_pos_id: String,
+ customer_ip: Secret<String, IpAddress>,
+ merchant_pos_id: Secret<String>,
description: String,
validity_time: Option<String>,
currency_code: enums::Currency,
@@ -417,12 +422,12 @@ pub struct PayuOrderResponseData {
#[serde(rename_all = "camelCase")]
pub struct PayuOrderResponseBuyerData {
ext_customer_id: Option<String>,
- email: Option<String>,
- phone: Option<String>,
- first_name: Option<String>,
- last_name: Option<String>,
+ email: Option<Email>,
+ phone: Option<Secret<String>>,
+ first_name: Option<Secret<String>>,
+ last_name: Option<Secret<String>>,
#[serde(rename = "nin")]
- national_identification_number: Option<String>,
+ national_identification_number: Option<Secret<String>>,
language: Option<String>,
delivery: Option<String>,
customer_id: Option<String>,
diff --git a/crates/router/src/connector/placetopay/transformers.rs b/crates/router/src/connector/placetopay/transformers.rs
index e5dedf6ded0..1c3b46fdb60 100644
--- a/crates/router/src/connector/placetopay/transformers.rs
+++ b/crates/router/src/connector/placetopay/transformers.rs
@@ -73,7 +73,7 @@ pub struct PlacetopayAuthType {
pub struct PlacetopayAuth {
login: Secret<String>,
tran_key: Secret<String>,
- nonce: String,
+ nonce: Secret<String>,
seed: String,
}
@@ -179,7 +179,7 @@ impl TryFrom<&types::ConnectorAuthType> for PlacetopayAuth {
context.update(seed.as_bytes());
context.update(placetopay_auth.tran_key.peek().as_bytes());
let encoded_digest = base64::Engine::encode(&consts::BASE64_ENGINE, context.finish());
- let nonce = base64::Engine::encode(&consts::BASE64_ENGINE, &nonce_bytes);
+ let nonce = Secret::new(base64::Engine::encode(&consts::BASE64_ENGINE, &nonce_bytes));
Ok(Self {
login: placetopay_auth.login,
tran_key: encoded_digest.into(),
diff --git a/crates/router/src/connector/powertranz.rs b/crates/router/src/connector/powertranz.rs
index 53f6a02d5b4..a26886384c0 100644
--- a/crates/router/src/connector/powertranz.rs
+++ b/crates/router/src/connector/powertranz.rs
@@ -309,7 +309,7 @@ impl
.get_redirect_response_payload()?
.parse_value("PowerTranz RedirectResponsePayload")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- let spi_token = format!(r#""{}""#, redirect_payload.spi_token);
+ let spi_token = format!(r#""{}""#, redirect_payload.spi_token.expose());
Ok(RequestContent::Json(Box::new(spi_token)))
}
diff --git a/crates/router/src/connector/powertranz/transformers.rs b/crates/router/src/connector/powertranz/transformers.rs
index 54849f8bf1d..0af5dde6d00 100644
--- a/crates/router/src/connector/powertranz/transformers.rs
+++ b/crates/router/src/connector/powertranz/transformers.rs
@@ -1,8 +1,8 @@
use api_models::payments::Card;
-use common_utils::pii::Email;
+use common_utils::pii::{Email, IpAddress};
use diesel_models::enums::RefundStatus;
use error_stack::IntoReport;
-use masking::Secret;
+use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
@@ -51,7 +51,7 @@ pub struct BrowserInfo {
screen_width: Option<String>,
time_zone: Option<String>,
user_agent: Option<String>,
- i_p: Option<std::net::IpAddr>,
+ i_p: Option<Secret<String, IpAddress>>,
color_depth: Option<String>,
}
@@ -94,7 +94,7 @@ pub struct PowertranzAddressDetails {
#[derive(Debug, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct RedirectResponsePayload {
- pub spi_token: String,
+ pub spi_token: Secret<String>,
}
impl TryFrom<&types::PaymentsAuthorizeRouterData> for PowertranzPaymentsRequest {
@@ -173,7 +173,9 @@ impl TryFrom<&types::BrowserInformation> for BrowserInfo {
screen_width: item.screen_width.map(|width| width.to_string()),
time_zone: item.time_zone.map(|zone| zone.to_string()),
user_agent: item.user_agent.clone(),
- i_p: item.ip_address,
+ i_p: item
+ .ip_address
+ .map(|ip_address| Secret::new(ip_address.to_string())),
color_depth: item.color_depth.map(|depth| depth.to_string()),
})
}
@@ -256,7 +258,7 @@ pub struct PowertranzBaseResponse {
original_trxn_identifier: Option<String>,
errors: Option<Vec<Error>>,
iso_response_code: String,
- redirect_data: Option<String>,
+ redirect_data: Option<Secret<String>>,
response_message: String,
order_identifier: String,
}
@@ -322,7 +324,7 @@ impl<F, T>
item.response
.redirect_data
.map(|redirect_data| services::RedirectForm::Html {
- html_data: redirect_data,
+ html_data: redirect_data.expose(),
});
let response = error_response.map_or(
Ok(types::PaymentsResponseData::TransactionResponse {
|
2024-03-04T06:54:02Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [x] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Mask pii information passed and received in the connector request and response for Payu, Placetopay, PowerTranz and Prophetpay.
## 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 Payu Google pay payment
Generate token from : https://jsfiddle.net/1agu74ve/1/
```
"gateway": "payu"
"gatewayMerchantId": "YOUR_GATEWAY_MERCHANT_ID"
```
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key:{}' \
--data-raw '{
"amount": 1800,
"currency": "PLN",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"customer_id": "CustomerX",
"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": "google_pay",
"payment_method_data": {
"wallet": {
"google_pay": {
"type": "CARD",
"description": "Visa •••• 1111",
"info": {
"card_network": "VISA",
"card_details": "1111"
},
"tokenization_data": {
"type": "PAYMENT_GATEWAY",
"token": "{{token}}"
}
}
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "Dubai",
"zip": "94122",
"country": "AE",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+97"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "AE",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"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"
},
"metadata": {
"count_tickets": 1,
"transaction_number": "5590043"
}
}'
```
2. PlaceToPay Card payment
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key:{{api_key}}' \
--data '{
"amount":320320,
"currency": "COP",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"customer_id": "deepanshu",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4110770010002837",
"card_exp_month": "02",
"card_exp_year": "26",
"card_holder_name": "joseph",
"card_cvc": "837"
}
},
"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",
"ip_address": "127.2.2.0"
}
}'
```
3. PowerTranz
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key:{{api_key}}' \
--data-raw '{
"amount": 20000,
"currency": "PLN",
"confirm": true,
"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://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"
}
},
"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"
},
"payment_method": "card",
"payment_method_data": {
"card": {
"card_number": "4000027891380961",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "Joseph Doe",
"card_cvc": "123"
}
}
}'
```
4. Check if all the sensitive data in the `masked_response` is masked
```
curl --location '{{base_url}}/analytics/v1/connector_event_logs?type=Payment&payment_id={{payment_id}}' \
--header 'sec-ch-ua: "Not A(Brand";v="99", "Google Chrome";v="121", "Chromium";v="121"' \
--header 'sec-ch-ua-mobile: ?0' \
--header 'authorization: Bearer JWT_token' \
--header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36' \
--header 'Content-Type: application/json' \
--header 'Referer: https://integ.hyperswitch.io/' \
--header 'api-key: {{api-key}}' \
--header 'sec-ch-ua-platform: "macOS"'
```
1. Payme Googlepay Response
```
"masked_response\":\"{\\\"status\\\":{\\\"statusCode\\\":\\\"WARNING_CONTINUE_3DS\\\",\\\"severity\\\":\\\"WARNING\\\",\\\"statusDesc\\\":null},\\\"redirectUri\\\":\\\"https://merch-prod.snd.payu.com/front/threeds/?authenticationId=d7b6aa7f-5aa8-467d-adcf-8a8ec9bee28a&refReqId=18c06b1d191d1cf26b93997134d7174d\\\",\\\"iframeAllowed\\\":true,\\\"threeDsProtocolVersion\\\":\\\"3DS2\\\",\\\"orderId\\\":\\\"T9L16ZMRD3240305GUEST000P01\\\",\\\"extOrderId\\\":null}
```
2. Placetopay Card payment
```
payment request\\\",\\\"amount\\\":{\\\"currency\\\":\\\"COP\\\",\\\"total\\\":320320}},\\\"instrument\\\":{\\\"card\\\":{\\\"number\\\":\\\"411077**********\\\",\\\"expiration\\\":\\\"*** alloc::string::String ***\\\",\\\"cvv\\\":\\\"*** alloc::string::String ***\\\"}},\\\"ipAddress\\\":\\\"127.**.**.**\\\",\\\"userAgent\\\":\\\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\\\"}\",\"masked_response\":\"{\\\"status\\\":{\\\"status\\\":\\\"APPROVED\\\"}
```
3. PowerTranz Card Payment
```
masked_response\":\"{\\\"TransactionType\\\":2,\\\"Approved\\\":false,\\\"TransactionIdentifier\\\":\\\"49da3e97-4f34-4a20-bbfd-204450646191\\\",\\\"OriginalTrxnIdentifier\\\":null,\\\"Errors\\\":null,\\\"IsoResponseCode\\\":\\\"SP4\\\",\\\"RedirectData\\\":\\\"*** alloc::string::String ***\\\",\\\"ResponseMessage\\\":\\\"SPI Preprocessing complete\\\",\\\"OrderIdentifier\\\":\\\"pay_C0D9yBw4FIxAiYSRMGJ2_1\\\"}
```
## Impacted Area
> Payme: Applepay and Googlepay
> Placetopay: Card Payment
> PowerTranz: Card Payment
## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
13f6d6c10ce421329a7eb8b494fbb3bd31aed91f
|
|
juspay/hyperswitch
|
juspay__hyperswitch-3927
|
Bug: [FEATURE] : [Payme][Payeezy] mask pii information in connector request and response
### Feature Description
Mask pii information passed and received in the connector request and response
### Possible Implementation
Refactor all sensitive response and request fields secret
### 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/payeezy/transformers.rs b/crates/router/src/connector/payeezy/transformers.rs
index 90b4b0b0bba..6d5d6db9dcf 100644
--- a/crates/router/src/connector/payeezy/transformers.rs
+++ b/crates/router/src/connector/payeezy/transformers.rs
@@ -1,7 +1,7 @@
use cards::CardNumber;
use common_utils::ext_traits::Encode;
use error_stack::ResultExt;
-use masking::Secret;
+use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
@@ -108,7 +108,7 @@ pub struct StoredCredentials {
pub sequence: Sequence,
pub initiator: Initiator,
pub is_scheduled: bool,
- pub cardbrand_original_transaction_id: Option<String>,
+ pub cardbrand_original_transaction_id: Option<Secret<String>>,
}
#[derive(Debug, Serialize, Deserialize)]
@@ -203,7 +203,7 @@ fn get_transaction_type_and_stored_creds(
},
is_scheduled: true,
// In case of first mandate payment connector_mandate_id would be None, otherwise holds some value
- cardbrand_original_transaction_id: connector_mandate_id,
+ cardbrand_original_transaction_id: connector_mandate_id.map(Secret::new),
}),
)
} else {
@@ -329,7 +329,7 @@ pub struct PayeezyPaymentsResponse {
#[derive(Debug, Deserialize, Serialize)]
pub struct PaymentsStoredCredentials {
- cardbrand_original_transaction_id: String,
+ cardbrand_original_transaction_id: Secret<String>,
}
#[derive(Debug, Serialize)]
@@ -416,7 +416,7 @@ impl<F, T>
.stored_credentials
.map(|credentials| credentials.cardbrand_original_transaction_id)
.map(|id| types::MandateReference {
- connector_mandate_id: Some(id),
+ connector_mandate_id: Some(id.expose()),
payment_method_id: None,
});
let status = enums::AttemptStatus::foreign_from((
diff --git a/crates/router/src/connector/payme/transformers.rs b/crates/router/src/connector/payme/transformers.rs
index ee0d52bae50..fd638f5b606 100644
--- a/crates/router/src/connector/payme/transformers.rs
+++ b/crates/router/src/connector/payme/transformers.rs
@@ -84,7 +84,7 @@ pub struct Pay3dsRequest {
buyer_email: pii::Email,
buyer_key: String,
payme_sale_id: String,
- meta_data_jwt: String,
+ meta_data_jwt: Secret<String>,
}
#[derive(Debug, Serialize)]
@@ -122,7 +122,7 @@ pub struct CaptureBuyerRequest {
#[derive(Debug, Deserialize, Serialize)]
pub struct CaptureBuyerResponse {
- buyer_key: String,
+ buyer_key: Secret<String>,
}
#[derive(Debug, Serialize)]
@@ -719,7 +719,7 @@ impl TryFrom<&types::PaymentsCompleteAuthorizeRouterData> for Pay3dsRequest {
buyer_key,
buyer_name,
payme_sale_id,
- meta_data_jwt: jwt_data.meta_data,
+ meta_data_jwt: Secret::new(jwt_data.meta_data),
})
}
Some(api::PaymentMethodData::CardRedirect(_))
@@ -902,10 +902,10 @@ impl<F, T>
) -> Result<Self, Self::Error> {
Ok(Self {
payment_method_token: Some(types::PaymentMethodToken::Token(
- item.response.buyer_key.clone(),
+ item.response.buyer_key.clone().expose(),
)),
response: Ok(types::PaymentsResponseData::TokenizationResponse {
- token: item.response.buyer_key,
+ token: item.response.buyer_key.expose(),
}),
..item.data
})
|
2024-03-04T06:33:46Z
|
## 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 -->
Mask pii information passed and received in the connector request and response for Payme and Payeezy.
## Test Case
<!--
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 3ds payment with payme
```
curl --location 'https://cee4-219-65-110-2.ngrok-free.app/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: {{api_key}}' \
--data-raw '{
"amount": 6540,
"currency": "USD",
"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": "three_ds",
"return_url": "https://duck.com",
"payment_method": "card",
"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": "PiX",
"last_name": "gnana"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "PiX",
"last_name": "gnana"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
},
"order_details": [
{
"product_name": "Apple iphone 15",
"quantity": 1,
"amount": 6540,
"account_name": "transaction_processing"
}
]
}'
```
1.b. Check if all the sensitive data in the `masked_response` is masked
```
curl --location '{{base_url}}/analytics/v1/connector_event_logs?type=Payment&payment_id={{payment_id}}' \
--header 'sec-ch-ua: "Not A(Brand";v="99", "Google Chrome";v="121", "Chromium";v="121"' \
--header 'sec-ch-ua-mobile: ?0' \
--header 'authorization: Bearer JWT_token' \
--header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36' \
--header 'Content-Type: application/json' \
--header 'Referer: https://integ.hyperswitch.io/' \
--header 'api-key: {{api-key}}' \
--header 'sec-ch-ua-platform: "macOS"'
```
Response
```
"masked_response\":\"{\\\"buyer_key\\\":\\\"*** alloc::string::String ***\\\"}
```
_Note: Don't have credentials to test payeezy_
## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
fee0663d665576cc80e0a8512fd8b36c91850332
|
|
juspay/hyperswitch
|
juspay__hyperswitch-3920
|
Bug: [BUG] hotfix: insert locker_id as null in case of payment method not getting stored in locker
If the payment is made with payment methods other than card and bank_transfer and is asked to save the payment method, we should store locker_id column as NULL in payment_methods table
|
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index 8c00938cadc..bea888dcce6 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -351,7 +351,13 @@ pub async fn add_payment_method(
None => {
let pm_metadata = resp.metadata.as_ref().map(|data| data.peek());
- let locker_id = Some(resp.payment_method_id);
+ let locker_id = if resp.payment_method == api_enums::PaymentMethod::Card
+ || resp.payment_method == api_enums::PaymentMethod::BankTransfer
+ {
+ Some(resp.payment_method_id)
+ } else {
+ None
+ };
resp.payment_method_id = generate_id(consts::ID_LENGTH, "pm");
insert_payment_method(
db,
diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs
index 21fd4cf85e8..1f793e2e185 100644
--- a/crates/router/src/core/payments/tokenization.rs
+++ b/crates/router/src/core/payments/tokenization.rs
@@ -1,4 +1,5 @@
use api_models::payment_methods::PaymentMethodsData;
+use common_enums::PaymentMethod;
use common_utils::{ext_traits::ValueExt, pii};
use error_stack::{report, ResultExt};
use masking::ExposeInterface;
@@ -342,7 +343,11 @@ where
None => {
let pm_metadata = create_payment_method_metadata(None, connector_token)?;
- locker_id = Some(resp.payment_method_id);
+ locker_id = if resp.payment_method == PaymentMethod::Card {
+ Some(resp.payment_method_id)
+ } else {
+ None
+ };
resp.payment_method_id = generate_id(consts::ID_LENGTH, "pm");
payment_methods::cards::create_payment_method(
db,
|
2024-03-01T15:28:11Z
|
## 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 -->
Main PR - https://github.com/juspay/hyperswitch/pull/3919
### 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
0bca3d757c58d425813c051e263febd8d385a587
|
|
juspay/hyperswitch
|
juspay__hyperswitch-3925
|
Bug: [FEATURE] : [Nuvei] mask pii information in connector request and response
### Feature Description
Mask pii information passed and received in the connector request and response
### Possible Implementation
Refactor all sensitive response and request fields secret
### 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/nuvei.rs b/crates/router/src/connector/nuvei.rs
index 8d3be455d49..0e9a9634402 100644
--- a/crates/router/src/connector/nuvei.rs
+++ b/crates/router/src/connector/nuvei.rs
@@ -9,6 +9,7 @@ use ::common_utils::{
request::RequestContent,
};
use error_stack::{IntoReport, ResultExt};
+use masking::ExposeInterface;
use transformers as nuvei;
use super::utils::{self, RouterData};
@@ -1010,7 +1011,7 @@ impl services::ConnectorRedirectResponse for Nuvei {
let redirect_response: nuvei::NuveiRedirectionResponse =
payload.parse_value("NuveiRedirectionResponse").switch()?;
let acs_response: nuvei::NuveiACSResponse =
- utils::base64_decode(redirect_response.cres)?
+ utils::base64_decode(redirect_response.cres.expose())?
.as_slice()
.parse_struct("NuveiACSResponse")
.switch()?;
diff --git a/crates/router/src/connector/nuvei/transformers.rs b/crates/router/src/connector/nuvei/transformers.rs
index 1312eadadf7..6c99536109b 100644
--- a/crates/router/src/connector/nuvei/transformers.rs
+++ b/crates/router/src/connector/nuvei/transformers.rs
@@ -3,12 +3,12 @@ use common_utils::{
crypto::{self, GenerateDigest},
date_time,
ext_traits::Encode,
- fp_utils, pii,
- pii::Email,
+ fp_utils,
+ pii::{Email, IpAddress},
};
use data_models::mandates::MandateDataType;
use error_stack::{IntoReport, ResultExt};
-use masking::{PeekInterface, Secret};
+use masking::{ExposeInterface, PeekInterface, Secret};
use reqwest::Url;
use serde::{Deserialize, Serialize};
@@ -26,7 +26,7 @@ use crate::{
#[derive(Debug, Serialize, Default, Deserialize)]
pub struct NuveiMeta {
- pub session_token: String,
+ pub session_token: Secret<String>,
}
#[derive(Debug, Serialize, Default, Deserialize)]
@@ -41,19 +41,19 @@ pub struct NuveiSessionRequest {
pub merchant_site_id: Secret<String>,
pub client_request_id: String,
pub time_stamp: date_time::DateTime<date_time::YYYYMMDDHHmmss>,
- pub checksum: String,
+ pub checksum: Secret<String>,
}
#[derive(Debug, Serialize, Default, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NuveiSessionResponse {
- pub session_token: String,
+ pub session_token: Secret<String>,
pub internal_request_id: i64,
pub status: String,
pub err_code: i64,
pub reason: String,
- pub merchant_id: String,
- pub merchant_site_id: String,
+ pub merchant_id: Secret<String>,
+ pub merchant_site_id: Secret<String>,
pub version: String,
pub client_request_id: String,
}
@@ -63,7 +63,7 @@ pub struct NuveiSessionResponse {
#[serde(rename_all = "camelCase")]
pub struct NuveiPaymentsRequest {
pub time_stamp: String,
- pub session_token: String,
+ pub session_token: Secret<String>,
pub merchant_id: Secret<String>,
pub merchant_site_id: Secret<String>,
pub client_request_id: Secret<String>,
@@ -76,7 +76,7 @@ pub struct NuveiPaymentsRequest {
pub is_rebilling: Option<String>,
pub payment_option: PaymentOption,
pub device_details: Option<DeviceDetails>,
- pub checksum: String,
+ pub checksum: Secret<String>,
pub billing_address: Option<BillingAddress>,
pub related_transaction_id: Option<String>,
pub url_details: Option<UrlDetails>,
@@ -92,14 +92,14 @@ pub struct UrlDetails {
#[derive(Debug, Serialize, Default)]
pub struct NuveiInitPaymentRequest {
- pub session_token: String,
- pub merchant_id: String,
- pub merchant_site_id: String,
+ pub session_token: Secret<String>,
+ pub merchant_id: Secret<String>,
+ pub merchant_site_id: Secret<String>,
pub client_request_id: String,
pub amount: String,
pub currency: String,
pub payment_option: PaymentOption,
- pub checksum: String,
+ pub checksum: Secret<String>,
}
/// Handles payment request for capture, void and refund flows
@@ -113,13 +113,13 @@ pub struct NuveiPaymentFlowRequest {
pub amount: String,
pub currency: diesel_models::enums::Currency,
pub related_transaction_id: Option<String>,
- pub checksum: String,
+ pub checksum: Secret<String>,
}
#[derive(Debug, Serialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct NuveiPaymentSyncRequest {
- pub session_token: String,
+ pub session_token: Secret<String>,
}
#[derive(Debug, Default, Serialize, Deserialize)]
@@ -217,12 +217,12 @@ pub struct Card {
#[serde(rename = "CVV")]
pub cvv: Option<Secret<String>>,
pub three_d: Option<ThreeD>,
- pub cc_card_number: Option<String>,
- pub bin: Option<String>,
- pub last4_digits: Option<String>,
- pub cc_exp_month: Option<String>,
- pub cc_exp_year: Option<String>,
- pub acquirer_id: Option<String>,
+ pub cc_card_number: Option<Secret<String>>,
+ pub bin: Option<Secret<String>>,
+ pub last4_digits: Option<Secret<String>>,
+ pub cc_exp_month: Option<Secret<String>>,
+ pub cc_exp_year: Option<Secret<String>>,
+ pub acquirer_id: Option<Secret<String>>,
pub cvv2_reply: Option<String>,
pub avs_code: Option<String>,
pub card_type: Option<String>,
@@ -260,7 +260,7 @@ pub struct ThreeD {
#[serde(rename = "merchantURL")]
pub merchant_url: Option<String>,
pub acs_url: Option<String>,
- pub c_req: Option<String>,
+ pub c_req: Option<Secret<String>>,
pub platform_type: Option<PlatformType>,
pub v2supported: Option<String>,
pub v2_additional_params: Option<V2AdditionalParams>,
@@ -291,7 +291,7 @@ pub enum PlatformType {
#[serde(rename_all = "camelCase")]
pub struct BrowserDetails {
pub accept_header: String,
- pub ip: Secret<String, pii::IpAddress>,
+ pub ip: Secret<String, IpAddress>,
pub java_enabled: String,
pub java_script_enabled: String,
pub language: String,
@@ -315,7 +315,7 @@ pub struct V2AdditionalParams {
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DeviceDetails {
- pub ip_address: Secret<String, pii::IpAddress>,
+ pub ip_address: Secret<String, IpAddress>,
}
impl From<enums::CaptureMethod> for TransactionType {
@@ -329,15 +329,15 @@ impl From<enums::CaptureMethod> for TransactionType {
#[derive(Debug, Serialize, Deserialize)]
pub struct NuveiRedirectionResponse {
- pub cres: String,
+ pub cres: Secret<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NuveiACSResponse {
#[serde(rename = "threeDSServerTransID")]
- pub three_ds_server_trans_id: String,
+ pub three_ds_server_trans_id: Secret<String>,
#[serde(rename = "acsTransID")]
- pub acs_trans_id: String,
+ pub acs_trans_id: Secret<String>,
pub message_type: String,
pub message_version: String,
pub trans_status: Option<LiabilityShift>,
@@ -394,13 +394,13 @@ impl TryFrom<&types::PaymentsAuthorizeSessionTokenRouterData> for NuveiSessionRe
merchant_site_id: merchant_site_id.clone(),
client_request_id: client_request_id.clone(),
time_stamp: time_stamp.clone(),
- checksum: encode_payload(&[
+ checksum: Secret::new(encode_payload(&[
merchant_id.peek(),
merchant_site_id.peek(),
&client_request_id,
&time_stamp.to_string(),
merchant_secret.peek(),
- ])?,
+ ])?),
})
}
}
@@ -415,9 +415,9 @@ impl<F, T>
) -> Result<Self, Self::Error> {
Ok(Self {
status: enums::AttemptStatus::Pending,
- session_token: Some(item.response.session_token.clone()),
+ session_token: Some(item.response.session_token.clone().expose()),
response: Ok(types::PaymentsResponseData::SessionTokenResponse {
- session_token: item.response.session_token,
+ session_token: item.response.session_token.expose(),
}),
..item.data
})
@@ -866,7 +866,7 @@ impl<F>
currency: item.request.currency,
connector_auth_type: item.connector_auth_type.clone(),
client_request_id: item.connector_request_reference_id.clone(),
- session_token: data.1,
+ session_token: Secret::new(data.1),
capture_method: item.request.capture_method,
..Default::default()
})?;
@@ -1015,10 +1015,12 @@ impl From<NuveiCardDetails> for PaymentOption {
}
}
-impl TryFrom<(&types::PaymentsCompleteAuthorizeRouterData, String)> for NuveiPaymentsRequest {
+impl TryFrom<(&types::PaymentsCompleteAuthorizeRouterData, Secret<String>)>
+ for NuveiPaymentsRequest
+{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- data: (&types::PaymentsCompleteAuthorizeRouterData, String),
+ data: (&types::PaymentsCompleteAuthorizeRouterData, Secret<String>),
) -> Result<Self, Self::Error> {
let item = data.0;
let request_data = match item.request.payment_method_data.clone() {
@@ -1067,7 +1069,7 @@ impl TryFrom<NuveiPaymentRequestData> for NuveiPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(request: NuveiPaymentRequestData) -> Result<Self, Self::Error> {
let session_token = request.session_token;
- fp_utils::when(session_token.is_empty(), || {
+ fp_utils::when(session_token.clone().expose().is_empty(), || {
Err(errors::ConnectorError::FailedToObtainAuthType)
})?;
let connector_meta: NuveiAuthType = NuveiAuthType::try_from(&request.connector_auth_type)?;
@@ -1089,7 +1091,7 @@ impl TryFrom<NuveiPaymentRequestData> for NuveiPaymentsRequest {
.capture_method
.map(TransactionType::from)
.unwrap_or_default(),
- checksum: encode_payload(&[
+ checksum: Secret::new(encode_payload(&[
merchant_id.peek(),
merchant_site_id.peek(),
&client_request_id,
@@ -1097,7 +1099,7 @@ impl TryFrom<NuveiPaymentRequestData> for NuveiPaymentsRequest {
&request.currency.to_string(),
&time_stamp,
merchant_secret.peek(),
- ])?,
+ ])?),
amount: request.amount,
currency: request.currency,
..Default::default()
@@ -1122,7 +1124,7 @@ impl TryFrom<NuveiPaymentRequestData> for NuveiPaymentFlowRequest {
merchant_site_id: merchant_site_id.to_owned(),
client_request_id: client_request_id.clone(),
time_stamp: time_stamp.clone(),
- checksum: encode_payload(&[
+ checksum: Secret::new(encode_payload(&[
merchant_id.peek(),
merchant_site_id.peek(),
&client_request_id,
@@ -1131,7 +1133,7 @@ impl TryFrom<NuveiPaymentRequestData> for NuveiPaymentFlowRequest {
&request.related_transaction_id.clone().unwrap_or_default(),
&time_stamp,
merchant_secret.peek(),
- ])?,
+ ])?),
amount: request.amount,
currency: request.currency,
related_transaction_id: request.related_transaction_id,
@@ -1146,7 +1148,7 @@ pub struct NuveiPaymentRequestData {
pub related_transaction_id: Option<String>,
pub client_request_id: String,
pub connector_auth_type: types::ConnectorAuthType,
- pub session_token: String,
+ pub session_token: Secret<String>,
pub capture_method: Option<diesel_models::enums::CaptureMethod>,
}
@@ -1273,7 +1275,7 @@ impl From<NuveiTransactionStatus> for enums::AttemptStatus {
#[serde(rename_all = "camelCase")]
pub struct NuveiPaymentsResponse {
pub order_id: Option<String>,
- pub user_token_id: Option<String>,
+ pub user_token_id: Option<Secret<String>>,
pub payment_option: Option<PaymentOption>,
pub transaction_status: Option<NuveiTransactionStatus>,
pub gw_error_code: Option<i64>,
@@ -1287,15 +1289,16 @@ pub struct NuveiPaymentsResponse {
pub auth_code: Option<String>,
pub custom_data: Option<String>,
pub fraud_details: Option<FraudDetails>,
- pub external_scheme_transaction_id: Option<String>,
- pub session_token: Option<String>,
+ pub external_scheme_transaction_id: Option<Secret<String>>,
+ pub session_token: Option<Secret<String>>,
+ //The ID of the transaction in the merchant’s system.
pub client_unique_id: Option<String>,
pub internal_request_id: Option<i64>,
pub status: NuveiPaymentStatus,
pub err_code: Option<i64>,
pub reason: Option<String>,
- pub merchant_id: Option<String>,
- pub merchant_site_id: Option<String>,
+ pub merchant_id: Option<Secret<String>>,
+ pub merchant_site_id: Option<Secret<String>>,
pub version: Option<String>,
pub client_request_id: Option<String>,
}
@@ -1417,7 +1420,10 @@ where
.map(|(base_url, creq)| services::RedirectForm::Form {
endpoint: base_url,
method: services::Method::Post,
- form_fields: std::collections::HashMap::from([("creq".to_string(), creq)]),
+ form_fields: std::collections::HashMap::from([(
+ "creq".to_string(),
+ creq.expose(),
+ )]),
}),
};
|
2024-03-04T06:23:42Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Bugfix
- [ ] New feature
- [x] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Mask pii information passed and received in the connector request and response for Nuvie.
## 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 card payment
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key:{{api_key}}' \
--data-raw '{
"amount": 20000,
"currency": "USD",
"confirm": true,
"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://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"
}
},
"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"
},
"payment_method": "card",
"payment_method_data": {
"card": {
"card_number": "4000027891380961",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "Joseph Doe",
"card_cvc": "123"
}
}
}'
```
2. Check if `subscription_data.identifier` in the `masked_response` is masked
```
curl --location '{{base_url}}/analytics/v1/connector_event_logs?type=Payment&payment_id={{payment_id}}' \
--header 'sec-ch-ua: "Not A(Brand";v="99", "Google Chrome";v="121", "Chromium";v="121"' \
--header 'sec-ch-ua-mobile: ?0' \
--header 'authorization: Bearer JWT_token' \
--header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36' \
--header 'Content-Type: application/json' \
--header 'Referer: https://integ.hyperswitch.io/' \
--header 'api-key: {{api-key}}' \
--header 'sec-ch-ua-platform: "macOS"'
```
Response
```
masked_response\":\"{\\\"orderId\\\":\\\"425682678\\\",\\\"userTokenId\\\":null,\\\"paymentOption\\\":{\\\"card\\\":{\\\"threeD\\\":{\\\"version\\\":\\\"\\\",\\\"cReq\\\":\\\"*** alloc::string::String ***\\\"},\\\"ccCardNumber\\\":\\\"*** alloc::string::String ***\\\",\\\"bin\\\":\\\"*** alloc::string::String ***\\\",\\\"last4Digits\\\":\\\"*** alloc::string::String ***\\\",\\\"ccExpMonth\\\":\\\"*** alloc::string::String ***\\\",\\\"ccExpYear\\\":\\\"*** alloc::string::String ***\\\",\\\"acquirerId\\\":\\\"*** alloc::string::String ***\\\",\\\"cvv2Reply\\\":\\\"\\\",\\\"avsCode\\\":\\\"\\\",\\\"cardType\\\":\\\"Credit\\\",\\\"cardBrand\\\":\\\"VISA\\\",\\\"issuerBankName\\\":\\\"River Valley Credit Union\\\",\\\"issuerCountry\\\":\\\"GB\\\",\\\"isPrepaid\\\":\\\"false\\\"},\\\"userPaymentOptionId\\\":\\\"\\\"},\\\"transactionStatus\\\":\\\"ERROR\\\",\\\"gwErrorCode\\\":-1,\\\"gwErrorReason\\\":\\\"UNEXPECTED SYSTEM ERROR - PLEASE RETRY LATER\\\",\\\"gwExtendedErrorCode\\\":-1,\\\"issuerDeclineCode\\\":\\\"\\\",\\\"issuerDeclineReason\\\":\\\"\\\",\\\"transactionType\\\":\\\"Auth3D\\\",\\\"transactionId\\\":\\\"711000000033006423\\\",\\\"externalTransactionId\\\":\\\"\\\",\\\"authCode\\\":\\\"\\\",\\\"customData\\\":\\\"\\\",\\\"fraudDetails\\\":null,\\\"externalSchemeTransactionId\\\":\\\"*** alloc::string::String ***\\\",\\\"sessionToken\\\":\\\"*** alloc::string::String ***\\\",\\\"clientUniqueId\\\":\\\"\\\",\\\"internalRequestId\\\":944545618,\\\"status\\\":\\\"SUCCESS\\\",\\\"errCode\\\":0,\\\"reason\\\":\\\"\\\",\\\"merchantId\\\":\\\"*** alloc::string::String ***\\\",\\\"merchantSiteId\\\":\\\"*** alloc::string::String ***\\\",\\\"version\\\":\\\"1.0\\\",\\\"clientRequestId\\\":\\\"pay_oVLDU95Hwm0D4tjm6CH6_1\\\"}
```
## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
0cb95a4911054e089e6ed3c528645ee1b881ebc6
|
|
juspay/hyperswitch
|
juspay__hyperswitch-3918
|
Bug: [BUG] insert `locker_id` as null in case of payment method not getting stored in locker
If the payment is made with payment methods other than card and bank_transfer and is asked to save the payment method, we should store `locker_id` column as `NULL` in payment_methods table
|
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index 4f691859215..ce7f48405e2 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -351,7 +351,13 @@ pub async fn add_payment_method(
None => {
let pm_metadata = resp.metadata.as_ref().map(|data| data.peek());
- let locker_id = Some(resp.payment_method_id);
+ let locker_id = if resp.payment_method == api_enums::PaymentMethod::Card
+ || resp.payment_method == api_enums::PaymentMethod::BankTransfer
+ {
+ Some(resp.payment_method_id)
+ } else {
+ None
+ };
resp.payment_method_id = generate_id(consts::ID_LENGTH, "pm");
insert_payment_method(
db,
diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs
index 21fd4cf85e8..1f793e2e185 100644
--- a/crates/router/src/core/payments/tokenization.rs
+++ b/crates/router/src/core/payments/tokenization.rs
@@ -1,4 +1,5 @@
use api_models::payment_methods::PaymentMethodsData;
+use common_enums::PaymentMethod;
use common_utils::{ext_traits::ValueExt, pii};
use error_stack::{report, ResultExt};
use masking::ExposeInterface;
@@ -342,7 +343,11 @@ where
None => {
let pm_metadata = create_payment_method_metadata(None, connector_token)?;
- locker_id = Some(resp.payment_method_id);
+ locker_id = if resp.payment_method == PaymentMethod::Card {
+ Some(resp.payment_method_id)
+ } else {
+ None
+ };
resp.payment_method_id = generate_id(consts::ID_LENGTH, "pm");
payment_methods::cards::create_payment_method(
db,
|
2024-03-01T14:58:08Z
|
## 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 -->
If the payment is made with payment methods other than card and bank_transfer and is asked to save the payment method, we should store `locker_id` column as `NULL` in payment_methods table.
### 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. Create an MCA
```
curl --location 'http://localhost:8080/account/merchant_1709304245/connectors' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"connector_type": "fiz_operations",
"connector_name": "stripe",
"business_label": "default",
"business_country": "US",
"connector_account_details": {
"auth_type": "HeaderKey",
"api_key": "abc"
},
"test_mode": true,
"disabled": false,
"payment_methods_enabled": [
{
"payment_method": "pay_later",
"payment_method_types": [
{
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true,
"payment_experience": "redirect_to_url",
"payment_method_type": "affirm"
}
]
},
{
"payment_method": "pay_later",
"payment_method_types": [
{
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true,
"payment_experience": "redirect_to_url",
"payment_method_type": "afterpay_clearpay"
}
]
},
{
"payment_method": "pay_later",
"payment_method_types": [
{
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true,
"payment_experience": "redirect_to_url",
"payment_method_type": "klarna"
}
]
},
{
"payment_method": "pay_later",
"payment_method_types": [
{
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true,
"payment_experience": "invoke_sdk_client",
"payment_method_type": "klarna"
}
]
},
{
"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_type": "google_pay",
"payment_experience": "invoke_sdk_client",
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
},
{
"payment_method": "bank_redirect",
"payment_method_types": [
{
"payment_method_type": "przelewy24",
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "blik",
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "ideal",
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "eps",
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "sofort",
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "giropay",
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
},
{
"payment_method": "bank_debit",
"payment_method_types": [
{
"payment_method_type": "sepa",
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "ach",
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "bacs",
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
},
{
"payment_method": "bank_transfer",
"payment_method_types": [
{
"payment_method_type": "ach",
"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": "sepa",
"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": "bacs",
"payment_experience": null,
"card_networks": null,
"accepted_currencies": null,
"accepted_countries": null,
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
}
]
}'
```
2. Create a bank debit payment
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_U44vOQtigGfoj1w2A0F0B9kLlXdZqTR8RRg3JwfPUJhLywIG4PdR1HZD0inVkS2f' \
--data-raw '{
"amount": 1800,
"currency": "USD",
"confirm": true,
"business_label": "default",
"capture_method": "automatic",
"customer_id": "klarna",
"capture_on": "2022-09-10T10:11:12Z",
"authentication_type": "three_ds",
"email": "guest1@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"return_url": "https://google.com",
"statement_descriptor_name": "Juspay",
"statement_descriptor_suffix": "Router",
"setup_future_usage": "off_session",
"business_country": "US",
"payment_method": "bank_debit",
"payment_method_type": "ach",
"payment_method_data": {
"bank_debit": {
"ach_bank_debit": {
"billing_details": {
"name": "John Doe",
"email": "johndoe@example.com"
},
"account_number": "000123456789",
"routing_number": "110000000"
}
}
},
"mandate_data": {
"customer_acceptance": {
"acceptance_type": "online",
"accepted_at": "2022-09-10T10:11:12Z",
"online": {
"ip_address": "123.32.25.123",
"user_agent": "Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36"
}
},
"mandate_type": {
"single_use": {
"amount": 6540,
"currency": "USD"
}
}
},
"metadata": {
"order_details": {
"product_name": "Apple iphone 15",
"quantity": 1,
"amount": 1800,
"account_name": "transaction_processing"
}
}
}'
```
In this case `locker_id` has to be NULL in payment_methods table

## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
816266819928477738f70b782eab0e26b600b171
|
|
juspay/hyperswitch
|
juspay__hyperswitch-3955
|
Bug: [BUG] [CI] NMI and Stripe CI failing
As we can see here in CI's commit, https://github.com/juspay/hyperswitch/commit/cd7040fa8cad2e69a53e3ed609c9eb8a8a17495a, it is clear that NMI and Stripe collection are the ones that are affected which again can be confirmed with https://github.com/juspay/hyperswitch/actions/runs/8148897592/job/22272607599
CI checks are failing.
|
diff --git a/crates/test_utils/src/main.rs b/crates/test_utils/src/main.rs
index 006075895b5..ba0d2eb358b 100644
--- a/crates/test_utils/src/main.rs
+++ b/crates/test_utils/src/main.rs
@@ -18,17 +18,21 @@ fn main() {
// Filter out None values leaving behind Some(Path)
let paths: Vec<String> = runner.modified_file_paths.into_iter().flatten().collect();
- let git_status = Command::new("git").arg("restore").args(&paths).output();
- match git_status {
- Ok(output) => {
- if !output.status.success() {
+ if !paths.is_empty() {
+ let git_status = Command::new("git").arg("restore").args(&paths).output();
+
+ match git_status {
+ Ok(output) if !output.status.success() => {
let stderr_str = String::from_utf8_lossy(&output.stderr);
eprintln!("Git command failed with error: {stderr_str}");
}
- }
- Err(e) => {
- eprintln!("Error running Git: {e}");
+ Ok(_) => {
+ println!("Git restore successful!");
+ }
+ Err(e) => {
+ eprintln!("Error running Git: {e}");
+ }
}
}
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9-Update amount with automatic capture/Payments - Confirm/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9-Update amount with automatic capture/Payments - Confirm/request.json
index 7b72495e5c4..9699acd8bb3 100644
--- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9-Update amount with automatic capture/Payments - Confirm/request.json
+++ b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9-Update amount with automatic capture/Payments - Confirm/request.json
@@ -29,7 +29,6 @@
"key": "Accept",
"value": "application/json"
},
- ,
{
"key": "publishable_key",
"value": "",
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9a-Update amount with manual capture/Payments - Confirm/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9a-Update amount with manual capture/Payments - Confirm/request.json
index 7b72495e5c4..9699acd8bb3 100644
--- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9a-Update amount with manual capture/Payments - Confirm/request.json
+++ b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9a-Update amount with manual capture/Payments - Confirm/request.json
@@ -29,7 +29,6 @@
"key": "Accept",
"value": "application/json"
},
- ,
{
"key": "publishable_key",
"value": "",
diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/.meta.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/.meta.json
index bfeee020b5d..016af982e9e 100644
--- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/.meta.json
+++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/.meta.json
@@ -30,6 +30,10 @@
"Scenario24-Add card flow",
"Scenario25-Don't Pass CVV for save card flow and verifysuccess payment",
"Scenario26-Save card payment with manual capture",
- "Scenario27-Create payment without customer_id and with billing address and shipping address"
+ "Scenario27-Create payment without customer_id and with billing address and shipping address",
+ "Scenario28-Confirm a payment with requires_customer_action status",
+ "Scenario29-Create payment with payment method billing",
+ "Scenario30-Update payment with payment method billing",
+ "Scenario31-Pass payment method billing in Confirm"
]
}
diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23- Update Amount/Payments - Confirm/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23- Update Amount/Payments - Confirm/request.json
index 5a51941cf64..2b86201e2fe 100644
--- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23- Update Amount/Payments - Confirm/request.json
+++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23- Update Amount/Payments - Confirm/request.json
@@ -29,7 +29,6 @@
"key": "Accept",
"value": "application/json"
},
- ,
{
"key": "publishable_key",
"value": "",
diff --git a/postman/collection-json/nmi.postman_collection.json b/postman/collection-json/nmi.postman_collection.json
index 3458081d489..89fd2e00d94 100644
--- a/postman/collection-json/nmi.postman_collection.json
+++ b/postman/collection-json/nmi.postman_collection.json
@@ -55,14 +55,7 @@
],
"request": {
"method": "GET",
- "header": [
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- }
- ],
+ "header": [],
"url": {
"raw": "{{baseUrl}}/health",
"host": [
@@ -6842,7 +6835,7 @@
"language": "json"
}
},
- "raw": "{\"amount\":\"{{another_random_number}}\"}"
+ "raw": "{\"amount\":\"{{another_random_number}}\",\"amount_to_capture\":\"{{another_random_number}}\"}"
},
"url": {
"raw": "{{baseUrl}}/payments/:id",
@@ -6956,12 +6949,6 @@
"key": "Accept",
"value": "application/json"
},
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- },
{
"key": "publishable_key",
"value": "",
@@ -7315,7 +7302,7 @@
"language": "json"
}
},
- "raw": "{\"amount\":\"{{another_random_number}}\"}"
+ "raw": "{\"amount\":\"{{another_random_number}}\",\"amount_to_capture\":\"{{another_random_number}}\"}"
},
"url": {
"raw": "{{baseUrl}}/payments/:id",
@@ -7429,12 +7416,6 @@
"key": "Accept",
"value": "application/json"
},
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- },
{
"key": "publishable_key",
"value": "",
diff --git a/postman/collection-json/stripe.postman_collection.json b/postman/collection-json/stripe.postman_collection.json
index 78a1777864a..e245b07fb97 100644
--- a/postman/collection-json/stripe.postman_collection.json
+++ b/postman/collection-json/stripe.postman_collection.json
@@ -55,14 +55,7 @@
],
"request": {
"method": "GET",
- "header": [
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- }
- ],
+ "header": [],
"url": {
"raw": "{{baseUrl}}/health",
"host": [
@@ -6722,10 +6715,10 @@
]
},
{
- "name": "Scenario28-Confirm a payment with requires_customer_action status",
+ "name": "Scenario1-Create payment with confirm true",
"item": [
{
- "name": "Payments - Create with confirm true",
+ "name": "Payments - Create",
"event": [
{
"listen": "test",
@@ -6793,21 +6786,21 @@
" );",
"}",
"",
- "// Response body should have value \"requires_customer_action\" for \"status\"",
+ "// Response body should have value \"succeeded\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments - Content check if value for 'status' matches 'requires_customer_action'\",",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",",
" function () {",
- " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
" },",
" );",
"}",
"",
- "// Response body should have \"next_action.redirect_to_url\"",
+ "// Response body should have \"connector_transaction_id\"",
"pm.test(",
- " \"[POST]::/payments - Content check if 'next_action.redirect_to_url' exists\",",
+ " \"[POST]::/payments - Content check if 'connector_transaction_id' exists\",",
" function () {",
- " pm.expect(typeof jsonData.next_action.redirect_to_url !== \"undefined\").to.be",
+ " pm.expect(typeof jsonData.connector_transaction_id !== \"undefined\").to.be",
" .true;",
" },",
");",
@@ -6836,7 +6829,7 @@
"language": "json"
}
},
- "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"business_country\":\"US\",\"business_label\":\"default\",\"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\",\"setup_future_usage\":\"on_session\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4000000000003063\",\"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\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"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\":6540,\"currency\":\"USD\",\"confirm\":true,\"business_country\":\"US\",\"business_label\":\"default\",\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"bernard123\",\"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://duck.com\",\"setup_future_usage\":\"on_session\",\"payment_method\":\"card\",\"payment_method_type\":\"debit\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"01\",\"card_exp_year\":\"26\",\"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\":\"sundari\",\"last_name\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\",\"last_name\":\"sundari\"}},\"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",
@@ -6852,15 +6845,15 @@
"response": []
},
{
- "name": "Payments - Confirm",
+ "name": "Payments - Retrieve",
"event": [
{
"listen": "test",
"script": {
"exec": [
"// Validate status 2xx",
- "pm.test(\"[GET]::/payments/:id - Status code is 400\", function () {",
- " pm.response.to.be.error;",
+ "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
@@ -6879,18 +6872,65 @@
"let jsonData = {};",
"try {",
" jsonData = pm.response.json();",
- "} catch (e) { }",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
"",
+ "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
+ "if (jsonData?.mandate_id) {",
+ " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ " console.log(",
+ " \"- use {{mandate_id}} as collection variable for value\",",
+ " jsonData.mandate_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
+ " );",
+ "}",
"",
- "// Response body should have appropriatae error message",
- "if (jsonData?.message) {",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"Succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
" pm.test(",
- " \"Content check if appropriate error message is present\",",
+ " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",",
" function () {",
- " pm.expect(jsonData.message).to.eql(\"You cannot confirm this payment because it has status requires_customer_action\");",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
" },",
" );",
"}",
+ "",
+ "// Response body should have \"connector_transaction_id\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'connector_transaction_id' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.connector_transaction_id !== \"undefined\").to.be",
+ " .true;",
+ " },",
+ ");",
""
],
"type": "text/javascript"
@@ -6898,55 +6938,27 @@
}
],
"request": {
- "auth": {
- "type": "apikey",
- "apikey": [
- {
- "key": "value",
- "value": "{{publishable_key}}",
- "type": "string"
- },
- {
- "key": "key",
- "value": "api-key",
- "type": "string"
- },
- {
- "key": "in",
- "value": "header",
- "type": "string"
- }
- ]
- },
- "method": "POST",
+ "method": "GET",
"header": [
- {
- "key": "Content-Type",
- "value": "application/json"
- },
{
"key": "Accept",
"value": "application/json"
}
],
- "body": {
- "mode": "raw",
- "options": {
- "raw": {
- "language": "json"
- }
- },
- "raw": "{\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"Joseph Doe\",\"card_cvc\":\"123\"}},\"client_secret\":\"{{client_secret}}\",\"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\":\"125.0.0.1\"}}"
- },
"url": {
- "raw": "{{baseUrl}}/payments/:id/confirm",
+ "raw": "{{baseUrl}}/payments/:id?force_sync=true",
"host": [
"{{baseUrl}}"
],
"path": [
"payments",
- ":id",
- "confirm"
+ ":id"
+ ],
+ "query": [
+ {
+ "key": "force_sync",
+ "value": "true"
+ }
],
"variable": [
{
@@ -6956,14 +6968,14 @@
}
]
},
- "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API"
+ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
},
"response": []
}
]
},
{
- "name": "Scenario29-Create payment with payment method billing",
+ "name": "Scenario2a-Create payment with confirm false card holder name null",
"item": [
{
"name": "Payments - Create",
@@ -6993,7 +7005,7 @@
"let jsonData = {};",
"try {",
" jsonData = pm.response.json();",
- "} catch (e) { }",
+ "} catch (e) {}",
"",
"// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
"if (jsonData?.payment_id) {",
@@ -7034,33 +7046,24 @@
" );",
"}",
"",
- "// Response body should have value \"succeeded\" for \"status\"",
+ "// Response body should have value \"requires_payment_method\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'\",",
" function () {",
- " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " pm.expect(jsonData.status).to.eql(\"requires_payment_method\");",
" },",
" );",
"}",
- "",
- "// Response body should have \"connector_transaction_id\"",
- "pm.test(",
- " \"[POST]::/payments - Content check if 'connector_transaction_id' exists\",",
- " function () {",
- " pm.expect(typeof jsonData.connector_transaction_id !== \"undefined\").to.be",
- " .true;",
- " },",
- ");",
- "",
- "// Response body should have \"payment_method_data.billing\"",
- "pm.test(",
- " \"[POST]::/payments - Content check if 'payment_method_data.billing' exists\",",
- " function () {",
- " pm.expect(typeof jsonData.payment_method_data.billing !== \"undefined\").to.be",
- " .true;",
- " },",
- ");",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ },
+ {
+ "listen": "prerequest",
+ "script": {
+ "exec": [
""
],
"type": "text/javascript"
@@ -7086,7 +7089,7 @@
"language": "json"
}
},
- "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"business_country\":\"US\",\"business_label\":\"default\",\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"bernard123\",\"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://duck.com\",\"setup_future_usage\":\"on_session\",\"payment_method\":\"card\",\"payment_method_type\":\"debit\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"01\",\"card_exp_year\":\"26\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrisoff Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"Narayan\",\"last_name\":\"Doe\"},\"email\":\"example@juspay.in\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\",\"last_name\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\",\"last_name\":\"sundari\"}},\"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\":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://duck.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"PiX\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"PiX\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
},
"url": {
"raw": "{{baseUrl}}/payments",
@@ -7102,26 +7105,29 @@
"response": []
},
{
- "name": "Payments - Retrieve",
+ "name": "Payments - Confirm",
"event": [
{
"listen": "test",
"script": {
"exec": [
"// Validate status 2xx",
- "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
+ "pm.test(\"[POST]::/payments/:id/confirm - Status code is 2xx\", function () {",
" pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
- "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
- " \"application/json\",",
- " );",
- "});",
+ "pm.test(",
+ " \"[POST]::/payments/:id/confirm - 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(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
+ "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {",
" pm.response.to.have.jsonBody();",
"});",
"",
@@ -7129,7 +7135,7 @@
"let jsonData = {};",
"try {",
" jsonData = pm.response.json();",
- "} catch (e) { }",
+ "} catch (e) {}",
"",
"// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
"if (jsonData?.payment_id) {",
@@ -7170,33 +7176,24 @@
" );",
"}",
"",
- "// Response body should have value \"Succeeded\" for \"status\"",
+ "// Response body should have value \"succeeded\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",",
+ " \"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'succeeded'\",",
" function () {",
" pm.expect(jsonData.status).to.eql(\"succeeded\");",
" },",
" );",
"}",
- "",
- "// Response body should have \"connector_transaction_id\"",
- "pm.test(",
- " \"[POST]::/payments - Content check if 'connector_transaction_id' exists\",",
- " function () {",
- " pm.expect(typeof jsonData.connector_transaction_id !== \"undefined\").to.be",
- " .true;",
- " },",
- ");",
- "",
- "// Response body should have \"payment_method_data.billing\"",
- "pm.test(",
- " \"[POST]::/payments - Content check if 'payment_method_data.billing' exists\",",
- " function () {",
- " pm.expect(typeof jsonData.payment_method_data.billing !== \"undefined\").to.be",
- " .true;",
- " },",
- ");",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ },
+ {
+ "listen": "prerequest",
+ "script": {
+ "exec": [
""
],
"type": "text/javascript"
@@ -7204,211 +7201,32 @@
}
],
"request": {
- "method": "GET",
+ "auth": {
+ "type": "apikey",
+ "apikey": [
+ {
+ "key": "value",
+ "value": "{{publishable_key}}",
+ "type": "string"
+ },
+ {
+ "key": "key",
+ "value": "api-key",
+ "type": "string"
+ },
+ {
+ "key": "in",
+ "value": "header",
+ "type": "string"
+ }
+ ]
+ },
+ "method": "POST",
"header": [
- {
- "key": "Accept",
- "value": "application/json"
- }
- ],
- "url": {
- "raw": "{{baseUrl}}/payments/:id?force_sync=true",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments",
- ":id"
- ],
- "query": [
- {
- "key": "force_sync",
- "value": "true"
- }
- ],
- "variable": [
- {
- "key": "id",
- "value": "{{payment_id}}",
- "description": "(Required) unique payment id"
- }
- ]
- },
- "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
- },
- "response": []
- }
- ]
- },
- {
- "name": "Scenario30-Update payment with payment method billing",
- "item": [
- {
- "name": "Payments - Create",
- "event": [
- {
- "listen": "test",
- "script": {
- "exec": [
- "// Validate status 2xx",
- "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
- "});",
- "",
- "// Validate if response header has matching content-type",
- "pm.test(\"[POST]::/payments - 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]::/payments - Response has JSON Body\", function () {",
- " pm.response.to.have.jsonBody();",
- "});",
- "",
- "// Set response object as internal variable",
- "let jsonData = {};",
- "try {",
- " jsonData = pm.response.json();",
- "} catch (e) { }",
- "",
- "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
- "if (jsonData?.payment_id) {",
- " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
- " console.log(",
- " \"- use {{payment_id}} as collection variable for value\",",
- " jsonData.payment_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
- " );",
- "}",
- "",
- "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
- "if (jsonData?.client_secret) {",
- " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
- " console.log(",
- " \"- use {{client_secret}} as collection variable for value\",",
- " jsonData.client_secret,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
- " );",
- "}",
- "",
- "// Response body should have value \"requires_payment_method\" for \"status\"",
- "if (jsonData?.status) {",
- " pm.test(",
- " \"[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'\",",
- " function () {",
- " pm.expect(jsonData.status).to.eql(\"requires_payment_method\");",
- " },",
- " );",
- "}",
- ""
- ],
- "type": "text/javascript"
- }
- }
- ],
- "request": {
- "method": "POST",
- "header": [
- {
- "key": "Content-Type",
- "value": "application/json"
- },
- {
- "key": "Accept",
- "value": "application/json"
- }
- ],
- "body": {
- "mode": "raw",
- "options": {
- "raw": {
- "language": "json"
- }
- },
- "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":false,\"business_country\":\"US\",\"business_label\":\"default\",\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"bernard123\",\"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://duck.com\",\"setup_future_usage\":\"on_session\",\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\",\"last_name\":\"sundari\"}},\"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",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments"
- ]
- },
- "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
- },
- "response": []
- },
- {
- "name": "Payments - Update",
- "event": [
- {
- "listen": "test",
- "script": {
- "exec": [
- "// Validate status 2xx",
- "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
- "});",
- "",
- "// Validate if response header has matching content-type",
- "pm.test(\"[POST]::/payments - 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]::/payments - Response has JSON Body\", function () {",
- " pm.response.to.have.jsonBody();",
- "});",
- "",
- "// Set response object as internal variable",
- "let jsonData = {};",
- "try {",
- " jsonData = pm.response.json();",
- "} catch (e) { }",
- "",
- "// Response body should have value \"requires_confirmation\" for \"status\"",
- "if (jsonData?.status) {",
- " pm.test(",
- " \"[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'\",",
- " function () {",
- " pm.expect(jsonData.status).to.eql(\"requires_confirmation\");",
- " },",
- " );",
- "}",
- "",
- "// Response body should have \"payment_method_data.billing\"",
- "pm.test(",
- " \"[POST]::/payments - Content check if 'payment_method_data.billing' exists\",",
- " function () {",
- " pm.expect(typeof jsonData.payment_method_data.billing !== \"undefined\").to.be",
- " .true;",
- " },",
- ");",
- ""
- ],
- "type": "text/javascript"
- }
- }
- ],
- "request": {
- "method": "POST",
- "header": [
- {
- "key": "Content-Type",
- "value": "application/json"
- },
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
{
"key": "Accept",
"value": "application/json"
@@ -7421,25 +7239,27 @@
"language": "json"
}
},
- "raw": "{\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"01\",\"card_exp_year\":\"26\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrisoff Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"Narayan\",\"last_name\":\"Doe\"},\"email\":\"example@juspay.in\"}}}"
+ "raw": "{\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":null,\"card_cvc\":\"123\"}},\"client_secret\":\"{{client_secret}}\",\"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\":\"125.0.0.1\"}}"
},
"url": {
- "raw": "{{baseUrl}}/payments/:id",
+ "raw": "{{baseUrl}}/payments/:id/confirm",
"host": [
"{{baseUrl}}"
],
"path": [
"payments",
- ":id"
+ ":id",
+ "confirm"
],
"variable": [
{
"key": "id",
- "value": "{{payment_id}}"
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
}
]
},
- "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API"
},
"response": []
},
@@ -7471,7 +7291,7 @@
"let jsonData = {};",
"try {",
" jsonData = pm.response.json();",
- "} catch (e) { }",
+ "} catch (e) {}",
"",
"// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
"if (jsonData?.payment_id) {",
@@ -7512,24 +7332,15 @@
" );",
"}",
"",
- "// Response body should have value \"requires_confirmation\" for \"status\"",
+ "// Response body should have value \"succeeded\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments/:id - Content check if value for 'status' matches 'requires_confirmation'\",",
+ " \"[POST]::/payments:id - Content check if value for 'status' matches 'succeeded'\",",
" function () {",
- " pm.expect(jsonData.status).to.eql(\"requires_confirmation\");",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
" },",
" );",
"}",
- "",
- "// Response body should have \"payment_method_data.billing\"",
- "pm.test(",
- " \"[POST]::/payments - Content check if 'payment_method_data.billing' exists\",",
- " function () {",
- " pm.expect(typeof jsonData.payment_method_data.billing !== \"undefined\").to.be",
- " .true;",
- " },",
- ");",
""
],
"type": "text/javascript"
@@ -7574,7 +7385,7 @@
]
},
{
- "name": "Scenario31-Pass payment method billing in Confirm",
+ "name": "Scenario2b-Create payment with confirm false card holder name empty",
"item": [
{
"name": "Payments - Create",
@@ -7711,7 +7522,7 @@
"script": {
"exec": [
"// Validate status 2xx",
- "pm.test(\"[POST]::/payments/:id/confirm - Status code is 2xx\", function () {",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
" pm.response.to.be.success;",
"});",
"",
@@ -7783,8 +7594,7 @@
" pm.expect(jsonData.status).to.eql(\"succeeded\");",
" },",
" );",
- "}",
- ""
+ "}"
],
"type": "text/javascript"
}
@@ -7838,7 +7648,7 @@
"language": "json"
}
},
- "raw": "{\"payment_method\":\"card\",\"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\":\"Harrisoff Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"Narayan\",\"last_name\":\"Doe\"},\"email\":\"example@juspay.in\"}},\"client_secret\":\"{{client_secret}}\",\"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\":\"125.0.0.1\"}}"
+ "raw": "{\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"\",\"card_cvc\":\"123\"}},\"client_secret\":\"{{client_secret}}\",\"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\":\"125.0.0.1\"}}"
},
"url": {
"raw": "{{baseUrl}}/payments/:id/confirm",
@@ -7890,7 +7700,7 @@
"let jsonData = {};",
"try {",
" jsonData = pm.response.json();",
- "} catch (e) { }",
+ "} catch (e) {}",
"",
"// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
"if (jsonData?.payment_id) {",
@@ -7939,17 +7749,7 @@
" pm.expect(jsonData.status).to.eql(\"succeeded\");",
" },",
" );",
- "}",
- "",
- "// Response body should have \"payment_method_data.billing\"",
- "pm.test(",
- " \"[POST]::/payments - Content check if 'payment_method_data.billing' exists\",",
- " function () {",
- " pm.expect(typeof jsonData.payment_method_data.billing !== \"undefined\").to.be",
- " .true;",
- " },",
- ");",
- ""
+ "}"
],
"type": "text/javascript"
}
@@ -7993,7 +7793,7 @@
]
},
{
- "name": "Scenario1-Create payment with confirm true",
+ "name": "Scenario3-Create payment without PMD",
"item": [
{
"name": "Payments - Create",
@@ -8064,24 +7864,144 @@
" );",
"}",
"",
- "// Response body should have value \"succeeded\" for \"status\"",
+ "// Response body should have value \"requires_payment_method\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'\",",
" function () {",
- " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " pm.expect(jsonData.status).to.eql(\"requires_payment_method\");",
" },",
" );",
"}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "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://duck.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"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",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Confirm",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments/:id/confirm - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
"",
- "// Response body should have \"connector_transaction_id\"",
+ "// Validate if response header has matching content-type",
"pm.test(",
- " \"[POST]::/payments - Content check if 'connector_transaction_id' exists\",",
+ " \"[POST]::/payments/:id/confirm - Content-Type is application/json\",",
" function () {",
- " pm.expect(typeof jsonData.connector_transaction_id !== \"undefined\").to.be",
- " .true;",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
" },",
");",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
+ "if (jsonData?.mandate_id) {",
+ " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ " console.log(",
+ " \"- use {{mandate_id}} as collection variable for value\",",
+ " jsonData.mandate_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments:id/confirm - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ },
+ {
+ "listen": "prerequest",
+ "script": {
+ "exec": [
""
],
"type": "text/javascript"
@@ -8089,6 +8009,26 @@
}
],
"request": {
+ "auth": {
+ "type": "apikey",
+ "apikey": [
+ {
+ "key": "value",
+ "value": "{{publishable_key}}",
+ "type": "string"
+ },
+ {
+ "key": "key",
+ "value": "api-key",
+ "type": "string"
+ },
+ {
+ "key": "in",
+ "value": "header",
+ "type": "string"
+ }
+ ]
+ },
"method": "POST",
"header": [
{
@@ -8107,18 +8047,27 @@
"language": "json"
}
},
- "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"business_country\":\"US\",\"business_label\":\"default\",\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"bernard123\",\"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://duck.com\",\"setup_future_usage\":\"on_session\",\"payment_method\":\"card\",\"payment_method_type\":\"debit\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"01\",\"card_exp_year\":\"26\",\"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\":\"sundari\",\"last_name\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\",\"last_name\":\"sundari\"}},\"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": "{\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"client_secret\":\"{{client_secret}}\"}"
},
"url": {
- "raw": "{{baseUrl}}/payments",
+ "raw": "{{baseUrl}}/payments/:id/confirm",
"host": [
"{{baseUrl}}"
],
"path": [
- "payments"
+ "payments",
+ ":id",
+ "confirm"
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
]
},
- "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API"
},
"response": []
},
@@ -8191,24 +8140,15 @@
" );",
"}",
"",
- "// Response body should have value \"Succeeded\" for \"status\"",
+ "// Response body should have value \"succeeded\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",",
+ " \"[POST]::/payments:id - Content check if value for 'status' matches 'succeeded'\",",
" function () {",
" pm.expect(jsonData.status).to.eql(\"succeeded\");",
" },",
" );",
"}",
- "",
- "// Response body should have \"connector_transaction_id\"",
- "pm.test(",
- " \"[POST]::/payments - Content check if 'connector_transaction_id' exists\",",
- " function () {",
- " pm.expect(typeof jsonData.connector_transaction_id !== \"undefined\").to.be",
- " .true;",
- " },",
- ");",
""
],
"type": "text/javascript"
@@ -8253,7 +8193,7 @@
]
},
{
- "name": "Scenario2a-Create payment with confirm false card holder name null",
+ "name": "Scenario4-Create payment with Manual capture",
"item": [
{
"name": "Payments - Create",
@@ -8324,12 +8264,12 @@
" );",
"}",
"",
- "// Response body should have value \"requires_payment_method\" for \"status\"",
+ "// Response body should have value \"requires_capture\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'\",",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'requires_capture'\",",
" function () {",
- " pm.expect(jsonData.status).to.eql(\"requires_payment_method\");",
+ " pm.expect(jsonData.status).to.eql(\"requires_capture\");",
" },",
" );",
"}",
@@ -8337,15 +8277,6 @@
],
"type": "text/javascript"
}
- },
- {
- "listen": "prerequest",
- "script": {
- "exec": [
- ""
- ],
- "type": "text/javascript"
- }
}
],
"request": {
@@ -8367,7 +8298,7 @@
"language": "json"
}
},
- "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://duck.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"PiX\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"PiX\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
+ "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"manual\",\"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://duck.com\",\"payment_method\":\"card\",\"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\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"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",
@@ -8383,20 +8314,20 @@
"response": []
},
{
- "name": "Payments - Confirm",
+ "name": "Payments - Capture",
"event": [
{
"listen": "test",
"script": {
"exec": [
"// Validate status 2xx",
- "pm.test(\"[POST]::/payments/:id/confirm - Status code is 2xx\", function () {",
+ "pm.test(\"[POST]::/payments/:id/capture - Status code is 2xx\", function () {",
" pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
"pm.test(",
- " \"[POST]::/payments/:id/confirm - Content-Type is application/json\",",
+ " \"[POST]::/payments/:id/capture - Content-Type is application/json\",",
" function () {",
" pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
" \"application/json\",",
@@ -8405,7 +8336,7 @@
");",
"",
"// Validate if response has JSON Body",
- "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {",
+ "pm.test(\"[POST]::/payments/:id/capture - Response has JSON Body\", function () {",
" pm.response.to.have.jsonBody();",
"});",
"",
@@ -8457,21 +8388,32 @@
"// Response body should have value \"succeeded\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'succeeded'\",",
+ " \"[POST]:://payments/:id/capture - Content check if value for 'status' matches 'succeeded'\",",
" function () {",
" pm.expect(jsonData.status).to.eql(\"succeeded\");",
" },",
" );",
"}",
- ""
- ],
- "type": "text/javascript"
- }
- },
- {
- "listen": "prerequest",
- "script": {
- "exec": [
+ "",
+ "// Response body should have value \"6540\" for \"amount\"",
+ "if (jsonData?.amount) {",
+ " pm.test(",
+ " \"[post]:://payments/:id/capture - Content check if value for 'amount' matches '6540'\",",
+ " function () {",
+ " pm.expect(jsonData.amount).to.eql(6540);",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"6000\" for \"amount_received\"",
+ "if (jsonData?.amount_received) {",
+ " pm.test(",
+ " \"[POST]::/payments:id/capture - Content check if value for 'amount_received' matches '6540'\",",
+ " function () {",
+ " pm.expect(jsonData.amount_received).to.eql(6540);",
+ " },",
+ " );",
+ "}",
""
],
"type": "text/javascript"
@@ -8479,26 +8421,6 @@
}
],
"request": {
- "auth": {
- "type": "apikey",
- "apikey": [
- {
- "key": "value",
- "value": "{{publishable_key}}",
- "type": "string"
- },
- {
- "key": "key",
- "value": "api-key",
- "type": "string"
- },
- {
- "key": "in",
- "value": "header",
- "type": "string"
- }
- ]
- },
"method": "POST",
"header": [
{
@@ -8517,17 +8439,17 @@
"language": "json"
}
},
- "raw": "{\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":null,\"card_cvc\":\"123\"}},\"client_secret\":\"{{client_secret}}\",\"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\":\"125.0.0.1\"}}"
+ "raw": "{\"amount_to_capture\":6540,\"statement_descriptor_name\":\"Joseph\",\"statement_descriptor_suffix\":\"JS\"}"
},
"url": {
- "raw": "{{baseUrl}}/payments/:id/confirm",
+ "raw": "{{baseUrl}}/payments/:id/capture",
"host": [
"{{baseUrl}}"
],
"path": [
"payments",
":id",
- "confirm"
+ "capture"
],
"variable": [
{
@@ -8537,7 +8459,7 @@
}
]
},
- "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API"
+ "description": "To capture the funds for an uncaptured payment"
},
"response": []
},
@@ -8613,7 +8535,7 @@
"// Response body should have value \"succeeded\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments:id - Content check if value for 'status' matches 'succeeded'\",",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",",
" function () {",
" pm.expect(jsonData.status).to.eql(\"succeeded\");",
" },",
@@ -8663,7 +8585,7 @@
]
},
{
- "name": "Scenario2b-Create payment with confirm false card holder name empty",
+ "name": "Scenario4a-Create payment with manual_multiple capture",
"item": [
{
"name": "Payments - Create",
@@ -8734,12 +8656,12 @@
" );",
"}",
"",
- "// Response body should have value \"requires_payment_method\" for \"status\"",
+ "// Response body should have value \"requires_capture\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'\",",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'requires_capture'\",",
" function () {",
- " pm.expect(jsonData.status).to.eql(\"requires_payment_method\");",
+ " pm.expect(jsonData.status).to.eql(\"requires_capture\");",
" },",
" );",
"}",
@@ -8747,15 +8669,6 @@
],
"type": "text/javascript"
}
- },
- {
- "listen": "prerequest",
- "script": {
- "exec": [
- ""
- ],
- "type": "text/javascript"
- }
}
],
"request": {
@@ -8777,7 +8690,7 @@
"language": "json"
}
},
- "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://duck.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"PiX\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"PiX\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
+ "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"manual\",\"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://duck.com\",\"payment_method\":\"card\",\"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\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"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",
@@ -8793,20 +8706,20 @@
"response": []
},
{
- "name": "Payments - Confirm",
+ "name": "Payments - Capture",
"event": [
{
"listen": "test",
"script": {
"exec": [
"// Validate status 2xx",
- "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ "pm.test(\"[POST]::/payments/:id/capture - Status code is 2xx\", function () {",
" pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
"pm.test(",
- " \"[POST]::/payments/:id/confirm - Content-Type is application/json\",",
+ " \"[POST]::/payments/:id/capture - Content-Type is application/json\",",
" function () {",
" pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
" \"application/json\",",
@@ -8815,7 +8728,7 @@
");",
"",
"// Validate if response has JSON Body",
- "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {",
+ "pm.test(\"[POST]::/payments/:id/capture - Response has JSON Body\", function () {",
" pm.response.to.have.jsonBody();",
"});",
"",
@@ -8867,20 +8780,32 @@
"// Response body should have value \"succeeded\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'succeeded'\",",
+ " \"[POST]:://payments/:id/capture - Content check if value for 'status' matches 'partially_captured'\",",
" function () {",
- " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " pm.expect(jsonData.status).to.eql(\"partially_captured\");",
" },",
" );",
- "}"
- ],
- "type": "text/javascript"
- }
- },
- {
- "listen": "prerequest",
- "script": {
- "exec": [
+ "}",
+ "",
+ "// Response body should have value \"6540\" for \"amount\"",
+ "if (jsonData?.amount) {",
+ " pm.test(",
+ " \"[post]:://payments/:id/capture - Content check if value for 'amount' matches '6540'\",",
+ " function () {",
+ " pm.expect(jsonData.amount).to.eql(6540);",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"6000\" for \"amount_received\"",
+ "if (jsonData?.amount_received) {",
+ " pm.test(",
+ " \"[POST]::/payments:id/capture - Content check if value for 'amount_received' matches '6000'\",",
+ " function () {",
+ " pm.expect(jsonData.amount_received).to.eql(6000);",
+ " },",
+ " );",
+ "}",
""
],
"type": "text/javascript"
@@ -8888,26 +8813,6 @@
}
],
"request": {
- "auth": {
- "type": "apikey",
- "apikey": [
- {
- "key": "value",
- "value": "{{publishable_key}}",
- "type": "string"
- },
- {
- "key": "key",
- "value": "api-key",
- "type": "string"
- },
- {
- "key": "in",
- "value": "header",
- "type": "string"
- }
- ]
- },
"method": "POST",
"header": [
{
@@ -8926,17 +8831,17 @@
"language": "json"
}
},
- "raw": "{\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"\",\"card_cvc\":\"123\"}},\"client_secret\":\"{{client_secret}}\",\"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\":\"125.0.0.1\"}}"
+ "raw": "{\"amount_to_capture\":6000,\"statement_descriptor_name\":\"Joseph\",\"statement_descriptor_suffix\":\"JS\"}"
},
"url": {
- "raw": "{{baseUrl}}/payments/:id/confirm",
+ "raw": "{{baseUrl}}/payments/:id/capture",
"host": [
"{{baseUrl}}"
],
"path": [
"payments",
":id",
- "confirm"
+ "capture"
],
"variable": [
{
@@ -8946,7 +8851,7 @@
}
]
},
- "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API"
+ "description": "To capture the funds for an uncaptured payment"
},
"response": []
},
@@ -9022,12 +8927,13 @@
"// Response body should have value \"succeeded\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments:id - Content check if value for 'status' matches 'succeeded'\",",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'partially_captured'\",",
" function () {",
- " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " pm.expect(jsonData.status).to.eql(\"partially_captured\");",
" },",
" );",
- "}"
+ "}",
+ ""
],
"type": "text/javascript"
}
@@ -9071,7 +8977,7 @@
]
},
{
- "name": "Scenario3-Create payment without PMD",
+ "name": "Scenario5-Void the payment",
"item": [
{
"name": "Payments - Create",
@@ -9142,12 +9048,12 @@
" );",
"}",
"",
- "// Response body should have value \"requires_payment_method\" for \"status\"",
+ "// Response body should have value \"requires_capture\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'\",",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'requires_capture'\",",
" function () {",
- " pm.expect(jsonData.status).to.eql(\"requires_payment_method\");",
+ " pm.expect(jsonData.status).to.eql(\"requires_capture\");",
" },",
" );",
"}",
@@ -9176,7 +9082,7 @@
"language": "json"
}
},
- "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://duck.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"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\":6540,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"manual\",\"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://duck.com\",\"payment_method\":\"card\",\"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\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"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",
@@ -9192,20 +9098,20 @@
"response": []
},
{
- "name": "Payments - Confirm",
+ "name": "Payments - Cancel",
"event": [
{
"listen": "test",
"script": {
"exec": [
"// Validate status 2xx",
- "pm.test(\"[POST]::/payments/:id/confirm - Status code is 2xx\", function () {",
+ "pm.test(\"[POST]::/payments/:id/cancel - Status code is 2xx\", function () {",
" pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
"pm.test(",
- " \"[POST]::/payments/:id/confirm - Content-Type is application/json\",",
+ " \"[POST]::/payments/:id/cancel - Content-Type is application/json\",",
" function () {",
" pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
" \"application/json\",",
@@ -9214,7 +9120,7 @@
");",
"",
"// Validate if response has JSON Body",
- "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {",
+ "pm.test(\"[POST]::/payments/:id/cancel - Response has JSON Body\", function () {",
" pm.response.to.have.jsonBody();",
"});",
"",
@@ -9237,19 +9143,6 @@
" );",
"}",
"",
- "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
- "if (jsonData?.mandate_id) {",
- " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
- " console.log(",
- " \"- use {{mandate_id}} as collection variable for value\",",
- " jsonData.mandate_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
- " );",
- "}",
- "",
"// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
"if (jsonData?.client_secret) {",
" pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
@@ -9262,12 +9155,13 @@
" \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
" );",
"}",
- "// Response body should have value \"succeeded\" for \"status\"",
+ "",
+ "// Response body should have value \"cancelled\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments:id/confirm - Content check if value for 'status' matches 'succeeded'\",",
+ " \"[POST]::/payments/:id/cancel - Content check if value for 'status' matches 'cancelled'\",",
" function () {",
- " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " pm.expect(jsonData.status).to.eql(\"cancelled\");",
" },",
" );",
"}",
@@ -9275,38 +9169,9 @@
],
"type": "text/javascript"
}
- },
- {
- "listen": "prerequest",
- "script": {
- "exec": [
- ""
- ],
- "type": "text/javascript"
- }
}
],
"request": {
- "auth": {
- "type": "apikey",
- "apikey": [
- {
- "key": "value",
- "value": "{{publishable_key}}",
- "type": "string"
- },
- {
- "key": "key",
- "value": "api-key",
- "type": "string"
- },
- {
- "key": "in",
- "value": "header",
- "type": "string"
- }
- ]
- },
"method": "POST",
"header": [
{
@@ -9325,17 +9190,17 @@
"language": "json"
}
},
- "raw": "{\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"client_secret\":\"{{client_secret}}\"}"
+ "raw": "{\"cancellation_reason\":\"requested_by_customer\"}"
},
"url": {
- "raw": "{{baseUrl}}/payments/:id/confirm",
+ "raw": "{{baseUrl}}/payments/:id/cancel",
"host": [
"{{baseUrl}}"
],
"path": [
"payments",
":id",
- "confirm"
+ "cancel"
],
"variable": [
{
@@ -9345,7 +9210,7 @@
}
]
},
- "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API"
+ "description": "A Payment could can be cancelled when it is in one of these statuses: requires_payment_method, requires_capture, requires_confirmation, requires_customer_action"
},
"response": []
},
@@ -9418,12 +9283,12 @@
" );",
"}",
"",
- "// Response body should have value \"succeeded\" for \"status\"",
+ "// Response body should have value \"cancelled\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments:id - Content check if value for 'status' matches 'succeeded'\",",
+ " \"[POST]::/payments/:id - Content check if value for 'status' matches 'cancelled'\",",
" function () {",
- " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " pm.expect(jsonData.status).to.eql(\"cancelled\");",
" },",
" );",
"}",
@@ -9471,7 +9336,7 @@
]
},
{
- "name": "Scenario4-Create payment with Manual capture",
+ "name": "Scenario6-Create 3DS payment",
"item": [
{
"name": "Payments - Create",
@@ -9542,15 +9407,24 @@
" );",
"}",
"",
- "// Response body should have value \"requires_capture\" for \"status\"",
+ "// Response body should have value \"requires_customer_action\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments - Content check if value for 'status' matches 'requires_capture'\",",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'requires_customer_action'\",",
" function () {",
- " pm.expect(jsonData.status).to.eql(\"requires_capture\");",
+ " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");",
" },",
" );",
"}",
+ "",
+ "// Response body should have \"next_action.redirect_to_url\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'next_action.redirect_to_url' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.next_action.redirect_to_url !== \"undefined\").to.be",
+ " .true;",
+ " },",
+ ");",
""
],
"type": "text/javascript"
@@ -9576,7 +9450,7 @@
"language": "json"
}
},
- "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"manual\",\"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://duck.com\",\"payment_method\":\"card\",\"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\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"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\":6540,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"business_country\":\"US\",\"business_label\":\"default\",\"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\",\"setup_future_usage\":\"on_session\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4000000000003063\",\"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\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"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",
@@ -9592,29 +9466,26 @@
"response": []
},
{
- "name": "Payments - Capture",
+ "name": "Payments - Retrieve",
"event": [
{
"listen": "test",
"script": {
"exec": [
"// Validate status 2xx",
- "pm.test(\"[POST]::/payments/:id/capture - Status code is 2xx\", function () {",
+ "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
" pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
- "pm.test(",
- " \"[POST]::/payments/:id/capture - Content-Type is application/json\",",
- " function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
- " \"application/json\",",
- " );",
- " },",
- ");",
+ "pm.test(\"[GET]::/payments/:id - 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]::/payments/:id/capture - Response has JSON Body\", function () {",
+ "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
" pm.response.to.have.jsonBody();",
"});",
"",
@@ -9663,32 +9534,12 @@
" );",
"}",
"",
- "// Response body should have value \"succeeded\" for \"status\"",
+ "// Response body should have value \"requires_customer_action\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]:://payments/:id/capture - Content check if value for 'status' matches 'succeeded'\",",
- " function () {",
- " pm.expect(jsonData.status).to.eql(\"succeeded\");",
- " },",
- " );",
- "}",
- "",
- "// Response body should have value \"6540\" for \"amount\"",
- "if (jsonData?.amount) {",
- " pm.test(",
- " \"[post]:://payments/:id/capture - Content check if value for 'amount' matches '6540'\",",
- " function () {",
- " pm.expect(jsonData.amount).to.eql(6540);",
- " },",
- " );",
- "}",
- "",
- "// Response body should have value \"6000\" for \"amount_received\"",
- "if (jsonData?.amount_received) {",
- " pm.test(",
- " \"[POST]::/payments:id/capture - Content check if value for 'amount_received' matches '6540'\",",
+ " \"[POST]::/payments/:id - Content check if value for 'status' matches 'requires_customer_action'\",",
" function () {",
- " pm.expect(jsonData.amount_received).to.eql(6540);",
+ " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");",
" },",
" );",
"}",
@@ -9699,137 +9550,10 @@
}
],
"request": {
- "method": "POST",
+ "method": "GET",
"header": [
{
- "key": "Content-Type",
- "value": "application/json"
- },
- {
- "key": "Accept",
- "value": "application/json"
- }
- ],
- "body": {
- "mode": "raw",
- "options": {
- "raw": {
- "language": "json"
- }
- },
- "raw": "{\"amount_to_capture\":6540,\"statement_descriptor_name\":\"Joseph\",\"statement_descriptor_suffix\":\"JS\"}"
- },
- "url": {
- "raw": "{{baseUrl}}/payments/:id/capture",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments",
- ":id",
- "capture"
- ],
- "variable": [
- {
- "key": "id",
- "value": "{{payment_id}}",
- "description": "(Required) unique payment id"
- }
- ]
- },
- "description": "To capture the funds for an uncaptured payment"
- },
- "response": []
- },
- {
- "name": "Payments - Retrieve",
- "event": [
- {
- "listen": "test",
- "script": {
- "exec": [
- "// Validate status 2xx",
- "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
- "});",
- "",
- "// Validate if response header has matching content-type",
- "pm.test(\"[GET]::/payments/:id - 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(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
- " pm.response.to.have.jsonBody();",
- "});",
- "",
- "// Set response object as internal variable",
- "let jsonData = {};",
- "try {",
- " jsonData = pm.response.json();",
- "} catch (e) {}",
- "",
- "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
- "if (jsonData?.payment_id) {",
- " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
- " console.log(",
- " \"- use {{payment_id}} as collection variable for value\",",
- " jsonData.payment_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
- " );",
- "}",
- "",
- "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
- "if (jsonData?.mandate_id) {",
- " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
- " console.log(",
- " \"- use {{mandate_id}} as collection variable for value\",",
- " jsonData.mandate_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
- " );",
- "}",
- "",
- "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
- "if (jsonData?.client_secret) {",
- " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
- " console.log(",
- " \"- use {{client_secret}} as collection variable for value\",",
- " jsonData.client_secret,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
- " );",
- "}",
- "",
- "// Response body should have value \"succeeded\" for \"status\"",
- "if (jsonData?.status) {",
- " pm.test(",
- " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",",
- " function () {",
- " pm.expect(jsonData.status).to.eql(\"succeeded\");",
- " },",
- " );",
- "}",
- ""
- ],
- "type": "text/javascript"
- }
- }
- ],
- "request": {
- "method": "GET",
- "header": [
- {
- "key": "Accept",
+ "key": "Accept",
"value": "application/json"
}
],
@@ -9863,7 +9587,7 @@
]
},
{
- "name": "Scenario4a-Create payment with manual_multiple capture",
+ "name": "Scenario7-Create 3DS payment with confrm false",
"item": [
{
"name": "Payments - Create",
@@ -9934,12 +9658,12 @@
" );",
"}",
"",
- "// Response body should have value \"requires_capture\" for \"status\"",
+ "// Response body should have value \"requires_confirmation\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments - Content check if value for 'status' matches 'requires_capture'\",",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'requires_confirmation'\",",
" function () {",
- " pm.expect(jsonData.status).to.eql(\"requires_capture\");",
+ " pm.expect(jsonData.status).to.eql(\"requires_confirmation\");",
" },",
" );",
"}",
@@ -9968,7 +9692,7 @@
"language": "json"
}
},
- "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"manual\",\"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://duck.com\",\"payment_method\":\"card\",\"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\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"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\":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\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4000000000003063\",\"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\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"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",
@@ -9984,20 +9708,20 @@
"response": []
},
{
- "name": "Payments - Capture",
+ "name": "Payments - Confirm",
"event": [
{
"listen": "test",
"script": {
"exec": [
"// Validate status 2xx",
- "pm.test(\"[POST]::/payments/:id/capture - Status code is 2xx\", function () {",
+ "pm.test(\"[POST]::/payments/:id/confirm - Status code is 2xx\", function () {",
" pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
"pm.test(",
- " \"[POST]::/payments/:id/capture - Content-Type is application/json\",",
+ " \"[POST]::/payments/:id/confirm - Content-Type is application/json\",",
" function () {",
" pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
" \"application/json\",",
@@ -10006,7 +9730,7 @@
");",
"",
"// Validate if response has JSON Body",
- "pm.test(\"[POST]::/payments/:id/capture - Response has JSON Body\", function () {",
+ "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {",
" pm.response.to.have.jsonBody();",
"});",
"",
@@ -10055,35 +9779,33 @@
" );",
"}",
"",
- "// Response body should have value \"succeeded\" for \"status\"",
+ "// Response body should have value \"requires_customer_action\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]:://payments/:id/capture - Content check if value for 'status' matches 'partially_captured'\",",
- " function () {",
- " pm.expect(jsonData.status).to.eql(\"partially_captured\");",
- " },",
- " );",
- "}",
- "",
- "// Response body should have value \"6540\" for \"amount\"",
- "if (jsonData?.amount) {",
- " pm.test(",
- " \"[post]:://payments/:id/capture - Content check if value for 'amount' matches '6540'\",",
+ " \"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'requires_customer_action'\",",
" function () {",
- " pm.expect(jsonData.amount).to.eql(6540);",
+ " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");",
" },",
" );",
"}",
"",
- "// Response body should have value \"6000\" for \"amount_received\"",
- "if (jsonData?.amount_received) {",
- " pm.test(",
- " \"[POST]::/payments:id/capture - Content check if value for 'amount_received' matches '6000'\",",
- " function () {",
- " pm.expect(jsonData.amount_received).to.eql(6000);",
- " },",
- " );",
- "}",
+ "// Response body should have \"next_action.redirect_to_url\"",
+ "pm.test(",
+ " \"[POST]::/payments/:id/confirm - Content check if 'next_action.redirect_to_url' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.next_action.redirect_to_url !== \"undefined\").to.be",
+ " .true;",
+ " },",
+ ");",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ },
+ {
+ "listen": "prerequest",
+ "script": {
+ "exec": [
""
],
"type": "text/javascript"
@@ -10091,6 +9813,26 @@
}
],
"request": {
+ "auth": {
+ "type": "apikey",
+ "apikey": [
+ {
+ "key": "value",
+ "value": "{{publishable_key}}",
+ "type": "string"
+ },
+ {
+ "key": "key",
+ "value": "api-key",
+ "type": "string"
+ },
+ {
+ "key": "in",
+ "value": "header",
+ "type": "string"
+ }
+ ]
+ },
"method": "POST",
"header": [
{
@@ -10109,17 +9851,17 @@
"language": "json"
}
},
- "raw": "{\"amount_to_capture\":6000,\"statement_descriptor_name\":\"Joseph\",\"statement_descriptor_suffix\":\"JS\"}"
+ "raw": "{\"client_secret\":\"{{client_secret}}\"}"
},
"url": {
- "raw": "{{baseUrl}}/payments/:id/capture",
+ "raw": "{{baseUrl}}/payments/:id/confirm",
"host": [
"{{baseUrl}}"
],
"path": [
"payments",
":id",
- "capture"
+ "confirm"
],
"variable": [
{
@@ -10129,7 +9871,7 @@
}
]
},
- "description": "To capture the funds for an uncaptured payment"
+ "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API"
},
"response": []
},
@@ -10202,12 +9944,12 @@
" );",
"}",
"",
- "// Response body should have value \"succeeded\" for \"status\"",
+ "// Response body should have value \"requires_customer_action\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments - Content check if value for 'status' matches 'partially_captured'\",",
+ " \"[POST]::/payments:id - Content check if value for 'status' matches 'requires_customer_action'\",",
" function () {",
- " pm.expect(jsonData.status).to.eql(\"partially_captured\");",
+ " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");",
" },",
" );",
"}",
@@ -10255,7 +9997,7 @@
]
},
{
- "name": "Scenario5-Void the payment",
+ "name": "Scenario8-Create a failure card payment with confirm true",
"item": [
{
"name": "Payments - Create",
@@ -10326,120 +10068,41 @@
" );",
"}",
"",
- "// Response body should have value \"requires_capture\" for \"status\"",
+ "// Response body should have value \"succeeded\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments - Content check if value for 'status' matches 'requires_capture'\",",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'failed'\",",
" function () {",
- " pm.expect(jsonData.status).to.eql(\"requires_capture\");",
+ " pm.expect(jsonData.status).to.eql(\"failed\");",
" },",
" );",
"}",
- ""
- ],
- "type": "text/javascript"
- }
- }
- ],
- "request": {
- "method": "POST",
- "header": [
- {
- "key": "Content-Type",
- "value": "application/json"
- },
- {
- "key": "Accept",
- "value": "application/json"
- }
- ],
- "body": {
- "mode": "raw",
- "options": {
- "raw": {
- "language": "json"
- }
- },
- "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"manual\",\"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://duck.com\",\"payment_method\":\"card\",\"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\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"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",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments"
- ]
- },
- "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
- },
- "response": []
- },
- {
- "name": "Payments - Cancel",
- "event": [
- {
- "listen": "test",
- "script": {
- "exec": [
- "// Validate status 2xx",
- "pm.test(\"[POST]::/payments/:id/cancel - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
- "});",
"",
- "// Validate if response header has matching content-type",
+ "// Response body should have \"connector_transaction_id\"",
"pm.test(",
- " \"[POST]::/payments/:id/cancel - Content-Type is application/json\",",
+ " \"[POST]::/payments - Content check if 'connector_transaction_id' exists\",",
" function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
- " \"application/json\",",
- " );",
+ " pm.expect(typeof jsonData.connector_transaction_id !== \"undefined\").to.be",
+ " .true;",
" },",
");",
"",
- "// Validate if response has JSON Body",
- "pm.test(\"[POST]::/payments/:id/cancel - Response has JSON Body\", function () {",
- " pm.response.to.have.jsonBody();",
- "});",
- "",
- "// Set response object as internal variable",
- "let jsonData = {};",
- "try {",
- " jsonData = pm.response.json();",
- "} catch (e) {}",
- "",
- "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
- "if (jsonData?.payment_id) {",
- " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
- " console.log(",
- " \"- use {{payment_id}} as collection variable for value\",",
- " jsonData.payment_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
- " );",
- "}",
- "",
- "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
- "if (jsonData?.client_secret) {",
- " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
- " console.log(",
- " \"- use {{client_secret}} as collection variable for value\",",
- " jsonData.client_secret,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ "// Response body should have value \"card_declined\" for \"error_code\"",
+ "if (jsonData?.error_code) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id/confirm - Content check if value for 'error_code' matches 'card_declined'\",",
+ " function () {",
+ " pm.expect(jsonData.error_code).to.eql(\"card_declined\");",
+ " },",
" );",
"}",
"",
- "// Response body should have value \"cancelled\" for \"status\"",
- "if (jsonData?.status) {",
+ "// Response body should have value \"message - Your card has insufficient funds., decline_code - insufficient_funds\" for \"error_message\"",
+ "if (jsonData?.error_message) {",
" pm.test(",
- " \"[POST]::/payments/:id/cancel - Content check if value for 'status' matches 'cancelled'\",",
+ " \"[POST]::/payments/:id/confirm - Content check if value for 'error_message' matches 'message - Your card has insufficient funds., decline_code - insufficient_funds'\",",
" function () {",
- " pm.expect(jsonData.status).to.eql(\"cancelled\");",
+ " pm.expect(jsonData.error_message).to.eql(\"message - Your card has insufficient funds., decline_code - insufficient_funds\");",
" },",
" );",
"}",
@@ -10468,27 +10131,18 @@
"language": "json"
}
},
- "raw": "{\"cancellation_reason\":\"requested_by_customer\"}"
+ "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"business_country\":\"US\",\"business_label\":\"default\",\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"bernard123\",\"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://duck.com\",\"setup_future_usage\":\"on_session\",\"payment_method\":\"card\",\"payment_method_type\":\"debit\",\"payment_method_data\":{\"card\":{\"card_number\":\"4000000000009995\",\"card_exp_month\":\"01\",\"card_exp_year\":\"26\",\"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\":\"sundari\",\"last_name\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\",\"last_name\":\"sundari\"}},\"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/:id/cancel",
+ "raw": "{{baseUrl}}/payments",
"host": [
"{{baseUrl}}"
],
"path": [
- "payments",
- ":id",
- "cancel"
- ],
- "variable": [
- {
- "key": "id",
- "value": "{{payment_id}}",
- "description": "(Required) unique payment id"
- }
+ "payments"
]
},
- "description": "A Payment could can be cancelled when it is in one of these statuses: requires_payment_method, requires_capture, requires_confirmation, requires_customer_action"
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
},
"response": []
},
@@ -10561,12 +10215,41 @@
" );",
"}",
"",
- "// Response body should have value \"cancelled\" for \"status\"",
+ "// Response body should have value \"Succeeded\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments/:id - Content check if value for 'status' matches 'cancelled'\",",
+ " \"[POST]::/payments/:id - Content check if value for 'status' matches 'failed'\",",
" function () {",
- " pm.expect(jsonData.status).to.eql(\"cancelled\");",
+ " pm.expect(jsonData.status).to.eql(\"failed\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have \"connector_transaction_id\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'connector_transaction_id' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.connector_transaction_id !== \"undefined\").to.be",
+ " .true;",
+ " },",
+ ");",
+ "",
+ "// Response body should have value \"card_declined\" for \"error_code\"",
+ "if (jsonData?.error_code) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id/confirm - Content check if value for 'error_code' matches 'card_declined'\",",
+ " function () {",
+ " pm.expect(jsonData.error_code).to.eql(\"card_declined\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"message - Your card has insufficient funds., decline_code - insufficient_funds\" for \"error_message\"",
+ "if (jsonData?.error_message) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id/confirm - Content check if value for 'error_message' matches 'message - Your card has insufficient funds., decline_code - insufficient_funds'\",",
+ " function () {",
+ " pm.expect(jsonData.error_message).to.eql(\"message - Your card has insufficient funds., decline_code - insufficient_funds\");",
" },",
" );",
"}",
@@ -10614,7 +10297,7 @@
]
},
{
- "name": "Scenario6-Create 3DS payment",
+ "name": "Scenario9-Refund full payment",
"item": [
{
"name": "Payments - Create",
@@ -10685,24 +10368,15 @@
" );",
"}",
"",
- "// Response body should have value \"requires_customer_action\" for \"status\"",
+ "// Response body should have value \"succeeded\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments - Content check if value for 'status' matches 'requires_customer_action'\",",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",",
" function () {",
- " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
" },",
" );",
"}",
- "",
- "// Response body should have \"next_action.redirect_to_url\"",
- "pm.test(",
- " \"[POST]::/payments - Content check if 'next_action.redirect_to_url' exists\",",
- " function () {",
- " pm.expect(typeof jsonData.next_action.redirect_to_url !== \"undefined\").to.be",
- " .true;",
- " },",
- ");",
""
],
"type": "text/javascript"
@@ -10728,7 +10402,7 @@
"language": "json"
}
},
- "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"business_country\":\"US\",\"business_label\":\"default\",\"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\",\"setup_future_usage\":\"on_session\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4000000000003063\",\"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\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"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\":6540,\"currency\":\"USD\",\"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\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"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\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"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",
@@ -10812,12 +10486,12 @@
" );",
"}",
"",
- "// Response body should have value \"requires_customer_action\" for \"status\"",
+ "// Response body should have value \"Succeeded\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments/:id - Content check if value for 'status' matches 'requires_customer_action'\",",
+ " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",",
" function () {",
- " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
" },",
" );",
"}",
@@ -10861,87 +10535,61 @@
"description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
},
"response": []
- }
- ]
- },
- {
- "name": "Scenario7-Create 3DS payment with confrm false",
- "item": [
+ },
{
- "name": "Payments - Create",
+ "name": "Refunds - Create",
"event": [
{
"listen": "test",
"script": {
"exec": [
"// Validate status 2xx",
- "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ "pm.test(\"[POST]::/refunds - Status code is 2xx\", function () {",
" pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
- "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ "pm.test(\"[POST]::/refunds - 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]::/payments - Response has JSON Body\", function () {",
- " pm.response.to.have.jsonBody();",
- "});",
- "",
"// Set response object as internal variable",
"let jsonData = {};",
"try {",
" jsonData = pm.response.json();",
"} catch (e) {}",
"",
- "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
- "if (jsonData?.payment_id) {",
- " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
- " console.log(",
- " \"- use {{payment_id}} as collection variable for value\",",
- " jsonData.payment_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
- " );",
- "}",
- "",
- "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
- "if (jsonData?.mandate_id) {",
- " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id",
+ "if (jsonData?.refund_id) {",
+ " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);",
" console.log(",
- " \"- use {{mandate_id}} as collection variable for value\",",
- " jsonData.mandate_id,",
+ " \"- use {{refund_id}} as collection variable for value\",",
+ " jsonData.refund_id,",
" );",
"} else {",
" console.log(",
- " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
+ " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",",
" );",
"}",
"",
- "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
- "if (jsonData?.client_secret) {",
- " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
- " console.log(",
- " \"- use {{client_secret}} as collection variable for value\",",
- " jsonData.client_secret,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/refunds - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
" );",
"}",
"",
- "// Response body should have value \"requires_confirmation\" for \"status\"",
+ "// Response body should have value \"6540\" for \"amount\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments - Content check if value for 'status' matches 'requires_confirmation'\",",
+ " \"[POST]::/refunds - Content check if value for 'amount' matches '6540'\",",
" function () {",
- " pm.expect(jsonData.status).to.eql(\"requires_confirmation\");",
+ " pm.expect(jsonData.amount).to.eql(6540);",
" },",
" );",
"}",
@@ -10970,46 +10618,38 @@
"language": "json"
}
},
- "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\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4000000000003063\",\"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\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"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": "{\"payment_id\":\"{{payment_id}}\",\"amount\":6540,\"reason\":\"Customer returned product\",\"refund_type\":\"instant\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
},
"url": {
- "raw": "{{baseUrl}}/payments",
+ "raw": "{{baseUrl}}/refunds",
"host": [
"{{baseUrl}}"
],
"path": [
- "payments"
+ "refunds"
]
},
- "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ "description": "To create a refund against an already processed payment"
},
"response": []
},
{
- "name": "Payments - Confirm",
+ "name": "Refunds - Retrieve",
"event": [
{
"listen": "test",
"script": {
"exec": [
"// Validate status 2xx",
- "pm.test(\"[POST]::/payments/:id/confirm - Status code is 2xx\", function () {",
+ "pm.test(\"[GET]::/refunds/:id - Status code is 2xx\", function () {",
" pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
- "pm.test(",
- " \"[POST]::/payments/:id/confirm - 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]::/payments/:id/confirm - Response has JSON Body\", function () {",
- " pm.response.to.have.jsonBody();",
+ "pm.test(\"[GET]::/refunds/:id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
"});",
"",
"// Set response object as internal variable",
@@ -11018,216 +10658,35 @@
" jsonData = pm.response.json();",
"} catch (e) {}",
"",
- "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
- "if (jsonData?.payment_id) {",
- " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
- " console.log(",
- " \"- use {{payment_id}} as collection variable for value\",",
- " jsonData.payment_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
- " );",
- "}",
- "",
- "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
- "if (jsonData?.mandate_id) {",
- " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
- " console.log(",
- " \"- use {{mandate_id}} as collection variable for value\",",
- " jsonData.mandate_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
- " );",
- "}",
- "",
- "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
- "if (jsonData?.client_secret) {",
- " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id",
+ "if (jsonData?.refund_id) {",
+ " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);",
" console.log(",
- " \"- use {{client_secret}} as collection variable for value\",",
- " jsonData.client_secret,",
+ " \"- use {{refund_id}} as collection variable for value\",",
+ " jsonData.refund_id,",
" );",
"} else {",
" console.log(",
- " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",",
" );",
"}",
"",
- "// Response body should have value \"requires_customer_action\" for \"status\"",
+ "// Response body should have value \"succeeded\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'requires_customer_action'\",",
+ " \"[POST]::/refunds - Content check if value for 'status' matches 'succeeded'\",",
" function () {",
- " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
" },",
" );",
"}",
"",
- "// Response body should have \"next_action.redirect_to_url\"",
- "pm.test(",
- " \"[POST]::/payments/:id/confirm - Content check if 'next_action.redirect_to_url' exists\",",
- " function () {",
- " pm.expect(typeof jsonData.next_action.redirect_to_url !== \"undefined\").to.be",
- " .true;",
- " },",
- ");",
- ""
- ],
- "type": "text/javascript"
- }
- },
- {
- "listen": "prerequest",
- "script": {
- "exec": [
- ""
- ],
- "type": "text/javascript"
- }
- }
- ],
- "request": {
- "auth": {
- "type": "apikey",
- "apikey": [
- {
- "key": "value",
- "value": "{{publishable_key}}",
- "type": "string"
- },
- {
- "key": "key",
- "value": "api-key",
- "type": "string"
- },
- {
- "key": "in",
- "value": "header",
- "type": "string"
- }
- ]
- },
- "method": "POST",
- "header": [
- {
- "key": "Content-Type",
- "value": "application/json"
- },
- {
- "key": "Accept",
- "value": "application/json"
- }
- ],
- "body": {
- "mode": "raw",
- "options": {
- "raw": {
- "language": "json"
- }
- },
- "raw": "{\"client_secret\":\"{{client_secret}}\"}"
- },
- "url": {
- "raw": "{{baseUrl}}/payments/:id/confirm",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments",
- ":id",
- "confirm"
- ],
- "variable": [
- {
- "key": "id",
- "value": "{{payment_id}}",
- "description": "(Required) unique payment id"
- }
- ]
- },
- "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API"
- },
- "response": []
- },
- {
- "name": "Payments - Retrieve",
- "event": [
- {
- "listen": "test",
- "script": {
- "exec": [
- "// Validate status 2xx",
- "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
- "});",
- "",
- "// Validate if response header has matching content-type",
- "pm.test(\"[GET]::/payments/:id - 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(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
- " pm.response.to.have.jsonBody();",
- "});",
- "",
- "// Set response object as internal variable",
- "let jsonData = {};",
- "try {",
- " jsonData = pm.response.json();",
- "} catch (e) {}",
- "",
- "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
- "if (jsonData?.payment_id) {",
- " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
- " console.log(",
- " \"- use {{payment_id}} as collection variable for value\",",
- " jsonData.payment_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
- " );",
- "}",
- "",
- "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
- "if (jsonData?.mandate_id) {",
- " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
- " console.log(",
- " \"- use {{mandate_id}} as collection variable for value\",",
- " jsonData.mandate_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
- " );",
- "}",
- "",
- "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
- "if (jsonData?.client_secret) {",
- " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
- " console.log(",
- " \"- use {{client_secret}} as collection variable for value\",",
- " jsonData.client_secret,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
- " );",
- "}",
- "",
- "// Response body should have value \"requires_customer_action\" for \"status\"",
+ "// Response body should have value \"6540\" for \"amount\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments:id - Content check if value for 'status' matches 'requires_customer_action'\",",
+ " \"[POST]::/refunds - Content check if value for 'amount' matches '6540'\",",
" function () {",
- " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");",
+ " pm.expect(jsonData.amount).to.eql(6540);",
" },",
" );",
"}",
@@ -11246,36 +10705,30 @@
}
],
"url": {
- "raw": "{{baseUrl}}/payments/:id?force_sync=true",
+ "raw": "{{baseUrl}}/refunds/:id",
"host": [
"{{baseUrl}}"
],
"path": [
- "payments",
+ "refunds",
":id"
],
- "query": [
- {
- "key": "force_sync",
- "value": "true"
- }
- ],
"variable": [
{
"key": "id",
- "value": "{{payment_id}}",
- "description": "(Required) unique payment id"
+ "value": "{{refund_id}}",
+ "description": "(Required) unique refund id"
}
]
},
- "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ "description": "To retrieve the properties of a Refund. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
},
"response": []
}
]
},
{
- "name": "Scenario8-Create a failure card payment with confirm true",
+ "name": "Scenario9a-Partial refund",
"item": [
{
"name": "Payments - Create",
@@ -11349,38 +10802,9 @@
"// Response body should have value \"succeeded\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments - Content check if value for 'status' matches 'failed'\",",
- " function () {",
- " pm.expect(jsonData.status).to.eql(\"failed\");",
- " },",
- " );",
- "}",
- "",
- "// Response body should have \"connector_transaction_id\"",
- "pm.test(",
- " \"[POST]::/payments - Content check if 'connector_transaction_id' exists\",",
- " function () {",
- " pm.expect(typeof jsonData.connector_transaction_id !== \"undefined\").to.be",
- " .true;",
- " },",
- ");",
- "",
- "// Response body should have value \"card_declined\" for \"error_code\"",
- "if (jsonData?.error_code) {",
- " pm.test(",
- " \"[POST]::/payments/:id/confirm - Content check if value for 'error_code' matches 'card_declined'\",",
- " function () {",
- " pm.expect(jsonData.error_code).to.eql(\"card_declined\");",
- " },",
- " );",
- "}",
- "",
- "// Response body should have value \"message - Your card has insufficient funds., decline_code - insufficient_funds\" for \"error_message\"",
- "if (jsonData?.error_message) {",
- " pm.test(",
- " \"[POST]::/payments/:id/confirm - Content check if value for 'error_message' matches 'message - Your card has insufficient funds., decline_code - insufficient_funds'\",",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",",
" function () {",
- " pm.expect(jsonData.error_message).to.eql(\"message - Your card has insufficient funds., decline_code - insufficient_funds\");",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
" },",
" );",
"}",
@@ -11409,7 +10833,7 @@
"language": "json"
}
},
- "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"business_country\":\"US\",\"business_label\":\"default\",\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"bernard123\",\"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://duck.com\",\"setup_future_usage\":\"on_session\",\"payment_method\":\"card\",\"payment_method_type\":\"debit\",\"payment_method_data\":{\"card\":{\"card_number\":\"4000000000009995\",\"card_exp_month\":\"01\",\"card_exp_year\":\"26\",\"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\":\"sundari\",\"last_name\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\",\"last_name\":\"sundari\"}},\"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\":6540,\"currency\":\"USD\",\"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\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"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\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"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",
@@ -11496,38 +10920,9 @@
"// Response body should have value \"Succeeded\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments/:id - Content check if value for 'status' matches 'failed'\",",
- " function () {",
- " pm.expect(jsonData.status).to.eql(\"failed\");",
- " },",
- " );",
- "}",
- "",
- "// Response body should have \"connector_transaction_id\"",
- "pm.test(",
- " \"[POST]::/payments - Content check if 'connector_transaction_id' exists\",",
- " function () {",
- " pm.expect(typeof jsonData.connector_transaction_id !== \"undefined\").to.be",
- " .true;",
- " },",
- ");",
- "",
- "// Response body should have value \"card_declined\" for \"error_code\"",
- "if (jsonData?.error_code) {",
- " pm.test(",
- " \"[POST]::/payments/:id/confirm - Content check if value for 'error_code' matches 'card_declined'\",",
- " function () {",
- " pm.expect(jsonData.error_code).to.eql(\"card_declined\");",
- " },",
- " );",
- "}",
- "",
- "// Response body should have value \"message - Your card has insufficient funds., decline_code - insufficient_funds\" for \"error_message\"",
- "if (jsonData?.error_message) {",
- " pm.test(",
- " \"[POST]::/payments/:id/confirm - Content check if value for 'error_message' matches 'message - Your card has insufficient funds., decline_code - insufficient_funds'\",",
+ " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",",
" function () {",
- " pm.expect(jsonData.error_message).to.eql(\"message - Your card has insufficient funds., decline_code - insufficient_funds\");",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
" },",
" );",
"}",
@@ -11571,87 +10966,61 @@
"description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
},
"response": []
- }
- ]
- },
- {
- "name": "Scenario9-Refund full payment",
- "item": [
+ },
{
- "name": "Payments - Create",
+ "name": "Refunds - Create",
"event": [
{
"listen": "test",
"script": {
"exec": [
"// Validate status 2xx",
- "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ "pm.test(\"[POST]::/refunds - Status code is 2xx\", function () {",
" pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
- "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ "pm.test(\"[POST]::/refunds - 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]::/payments - Response has JSON Body\", function () {",
- " pm.response.to.have.jsonBody();",
- "});",
- "",
"// Set response object as internal variable",
"let jsonData = {};",
"try {",
" jsonData = pm.response.json();",
"} catch (e) {}",
"",
- "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
- "if (jsonData?.payment_id) {",
- " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
- " console.log(",
- " \"- use {{payment_id}} as collection variable for value\",",
- " jsonData.payment_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
- " );",
- "}",
- "",
- "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
- "if (jsonData?.mandate_id) {",
- " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id",
+ "if (jsonData?.refund_id) {",
+ " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);",
" console.log(",
- " \"- use {{mandate_id}} as collection variable for value\",",
- " jsonData.mandate_id,",
+ " \"- use {{refund_id}} as collection variable for value\",",
+ " jsonData.refund_id,",
" );",
"} else {",
" console.log(",
- " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
+ " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",",
" );",
"}",
"",
- "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
- "if (jsonData?.client_secret) {",
- " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
- " console.log(",
- " \"- use {{client_secret}} as collection variable for value\",",
- " jsonData.client_secret,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/refunds - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
" );",
"}",
"",
- "// Response body should have value \"succeeded\" for \"status\"",
+ "// Response body should have value \"540\" for \"amount\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",",
+ " \"[POST]::/refunds - Content check if value for 'amount' matches '540'\",",
" function () {",
- " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " pm.expect(jsonData.amount).to.eql(540);",
" },",
" );",
"}",
@@ -11680,96 +11049,75 @@
"language": "json"
}
},
- "raw": "{\"amount\":6540,\"currency\":\"USD\",\"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\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"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\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"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": "{\"payment_id\":\"{{payment_id}}\",\"amount\":540,\"reason\":\"Customer returned product\",\"refund_type\":\"instant\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
},
"url": {
- "raw": "{{baseUrl}}/payments",
+ "raw": "{{baseUrl}}/refunds",
"host": [
"{{baseUrl}}"
],
"path": [
- "payments"
+ "refunds"
]
},
- "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ "description": "To create a refund against an already processed payment"
},
"response": []
},
{
- "name": "Payments - Retrieve",
+ "name": "Refunds - Retrieve",
"event": [
{
"listen": "test",
"script": {
"exec": [
"// Validate status 2xx",
- "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
+ "pm.test(\"[GET]::/refunds/:id - Status code is 2xx\", function () {",
" pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
- "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {",
+ "pm.test(\"[GET]::/refunds/:id - 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(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
- " pm.response.to.have.jsonBody();",
- "});",
- "",
"// Set response object as internal variable",
"let jsonData = {};",
"try {",
" jsonData = pm.response.json();",
"} catch (e) {}",
"",
- "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
- "if (jsonData?.payment_id) {",
- " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
- " console.log(",
- " \"- use {{payment_id}} as collection variable for value\",",
- " jsonData.payment_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
- " );",
- "}",
- "",
- "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
- "if (jsonData?.mandate_id) {",
- " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id",
+ "if (jsonData?.refund_id) {",
+ " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);",
" console.log(",
- " \"- use {{mandate_id}} as collection variable for value\",",
- " jsonData.mandate_id,",
+ " \"- use {{refund_id}} as collection variable for value\",",
+ " jsonData.refund_id,",
" );",
"} else {",
" console.log(",
- " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
+ " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",",
" );",
"}",
"",
- "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
- "if (jsonData?.client_secret) {",
- " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
- " console.log(",
- " \"- use {{client_secret}} as collection variable for value\",",
- " jsonData.client_secret,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/refunds - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
" );",
"}",
"",
- "// Response body should have value \"Succeeded\" for \"status\"",
+ "// Response body should have value \"6540\" for \"amount\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",",
+ " \"[POST]::/refunds - Content check if value for 'amount' matches '540'\",",
" function () {",
- " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " pm.expect(jsonData.amount).to.eql(540);",
" },",
" );",
"}",
@@ -11788,34 +11136,28 @@
}
],
"url": {
- "raw": "{{baseUrl}}/payments/:id?force_sync=true",
+ "raw": "{{baseUrl}}/refunds/:id",
"host": [
"{{baseUrl}}"
],
"path": [
- "payments",
+ "refunds",
":id"
],
- "query": [
- {
- "key": "force_sync",
- "value": "true"
- }
- ],
"variable": [
{
"key": "id",
- "value": "{{payment_id}}",
- "description": "(Required) unique payment id"
+ "value": "{{refund_id}}",
+ "description": "(Required) unique refund id"
}
]
},
- "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ "description": "To retrieve the properties of a Refund. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
},
"response": []
},
{
- "name": "Refunds - Create",
+ "name": "Refunds - Create-copy",
"event": [
{
"listen": "test",
@@ -11862,12 +11204,12 @@
" );",
"}",
"",
- "// Response body should have value \"6540\" for \"amount\"",
+ "// Response body should have value \"1000\" for \"amount\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/refunds - Content check if value for 'amount' matches '6540'\",",
+ " \"[POST]::/refunds - Content check if value for 'amount' matches '1000'\",",
" function () {",
- " pm.expect(jsonData.amount).to.eql(6540);",
+ " pm.expect(jsonData.amount).to.eql(1000);",
" },",
" );",
"}",
@@ -11896,7 +11238,7 @@
"language": "json"
}
},
- "raw": "{\"payment_id\":\"{{payment_id}}\",\"amount\":6540,\"reason\":\"Customer returned product\",\"refund_type\":\"instant\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
+ "raw": "{\"payment_id\":\"{{payment_id}}\",\"amount\":1000,\"reason\":\"Customer returned product\",\"refund_type\":\"instant\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
},
"url": {
"raw": "{{baseUrl}}/refunds",
@@ -11912,7 +11254,7 @@
"response": []
},
{
- "name": "Refunds - Retrieve",
+ "name": "Refunds - Retrieve-copy",
"event": [
{
"listen": "test",
@@ -11962,9 +11304,9 @@
"// Response body should have value \"6540\" for \"amount\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/refunds - Content check if value for 'amount' matches '6540'\",",
+ " \"[POST]::/refunds - Content check if value for 'amount' matches '1000'\",",
" function () {",
- " pm.expect(jsonData.amount).to.eql(6540);",
+ " pm.expect(jsonData.amount).to.eql(1000);",
" },",
" );",
"}",
@@ -12002,33 +11344,28 @@
"description": "To retrieve the properties of a Refund. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
},
"response": []
- }
- ]
- },
- {
- "name": "Scenario9a-Partial refund",
- "item": [
+ },
{
- "name": "Payments - Create",
+ "name": "Payments - Retrieve-copy",
"event": [
{
"listen": "test",
"script": {
"exec": [
"// Validate status 2xx",
- "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
" pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
- "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ "pm.test(\"[GET]::/payments/:id - 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]::/payments - Response has JSON Body\", function () {",
+ "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
" pm.response.to.have.jsonBody();",
"});",
"",
@@ -12077,15 +11414,20 @@
" );",
"}",
"",
- "// Response body should have value \"succeeded\" for \"status\"",
+ "// Response body should have value \"Succeeded\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",",
+ " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",",
" function () {",
" pm.expect(jsonData.status).to.eql(\"succeeded\");",
" },",
" );",
"}",
+ "",
+ "// Response body should have \"refunds\"",
+ "pm.test(\"[POST]::/payments - Content check if 'refunds' exists\", function () {",
+ " pm.expect(typeof jsonData.refunds !== \"undefined\").to.be.true;",
+ "});",
""
],
"type": "text/javascript"
@@ -12093,60 +11435,66 @@
}
],
"request": {
- "method": "POST",
+ "method": "GET",
"header": [
- {
- "key": "Content-Type",
- "value": "application/json"
- },
{
"key": "Accept",
"value": "application/json"
}
],
- "body": {
- "mode": "raw",
- "options": {
- "raw": {
- "language": "json"
- }
- },
- "raw": "{\"amount\":6540,\"currency\":\"USD\",\"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\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"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\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"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",
+ "raw": "{{baseUrl}}/payments/:id?force_sync=true",
"host": [
"{{baseUrl}}"
],
"path": [
- "payments"
+ "payments",
+ ":id"
+ ],
+ "query": [
+ {
+ "key": "force_sync",
+ "value": "true"
+ }
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
]
},
- "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
},
"response": []
- },
+ }
+ ]
+ },
+ {
+ "name": "Scenario10-Create a mandate and recurring payment",
+ "item": [
{
- "name": "Payments - Retrieve",
+ "name": "Payments - Create",
"event": [
{
"listen": "test",
"script": {
"exec": [
"// Validate status 2xx",
- "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
" pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
- "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {",
+ "pm.test(\"[POST]::/payments - 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(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
" pm.response.to.have.jsonBody();",
"});",
"",
@@ -12195,113 +11543,41 @@
" );",
"}",
"",
- "// Response body should have value \"Succeeded\" for \"status\"",
+ "// Response body should have value \"succeeded\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",",
" function () {",
" pm.expect(jsonData.status).to.eql(\"succeeded\");",
" },",
" );",
"}",
- ""
- ],
- "type": "text/javascript"
- }
- }
- ],
- "request": {
- "method": "GET",
- "header": [
- {
- "key": "Accept",
- "value": "application/json"
- }
- ],
- "url": {
- "raw": "{{baseUrl}}/payments/:id?force_sync=true",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments",
- ":id"
- ],
- "query": [
- {
- "key": "force_sync",
- "value": "true"
- }
- ],
- "variable": [
- {
- "key": "id",
- "value": "{{payment_id}}",
- "description": "(Required) unique payment id"
- }
- ]
- },
- "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
- },
- "response": []
- },
- {
- "name": "Refunds - Create",
- "event": [
- {
- "listen": "test",
- "script": {
- "exec": [
- "// Validate status 2xx",
- "pm.test(\"[POST]::/refunds - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
- "});",
- "",
- "// Validate if response header has matching content-type",
- "pm.test(\"[POST]::/refunds - Content-Type is application/json\", function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
- " \"application/json\",",
- " );",
- "});",
- "",
- "// Set response object as internal variable",
- "let jsonData = {};",
- "try {",
- " jsonData = pm.response.json();",
- "} catch (e) {}",
- "",
- "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id",
- "if (jsonData?.refund_id) {",
- " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);",
- " console.log(",
- " \"- use {{refund_id}} as collection variable for value\",",
- " jsonData.refund_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",",
- " );",
- "}",
"",
"// Response body should have value \"succeeded\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/refunds - Content check if value for 'status' matches 'succeeded'\",",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",",
" function () {",
" pm.expect(jsonData.status).to.eql(\"succeeded\");",
" },",
" );",
"}",
"",
- "// Response body should have value \"540\" for \"amount\"",
- "if (jsonData?.status) {",
- " pm.test(",
- " \"[POST]::/refunds - Content check if value for 'amount' matches '540'\",",
- " function () {",
- " pm.expect(jsonData.amount).to.eql(540);",
- " },",
- " );",
- "}",
+ "// Response body should have \"mandate_id\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_id' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ "",
+ "// Response body should have \"mandate_data\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_data' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;",
+ " },",
+ ");",
""
],
"type": "text/javascript"
@@ -12327,78 +11603,115 @@
"language": "json"
}
},
- "raw": "{\"payment_id\":\"{{payment_id}}\",\"amount\":540,\"reason\":\"Customer returned product\",\"refund_type\":\"instant\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
+ "raw": "{\"amount\":6540,\"currency\":\"USD\",\"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\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"setup_future_usage\":\"off_session\",\"mandate_data\":{\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"127.0.0.1\",\"user_agent\":\"amet irure esse\"}},\"mandate_type\":{\"single_use\":{\"amount\":7000,\"currency\":\"USD\"}}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"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}}/refunds",
+ "raw": "{{baseUrl}}/payments",
"host": [
"{{baseUrl}}"
],
"path": [
- "refunds"
+ "payments"
]
},
- "description": "To create a refund against an already processed payment"
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
},
"response": []
},
{
- "name": "Refunds - Retrieve",
+ "name": "Payments - Retrieve",
"event": [
{
"listen": "test",
"script": {
"exec": [
"// Validate status 2xx",
- "pm.test(\"[GET]::/refunds/:id - Status code is 2xx\", function () {",
+ "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
" pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
- "pm.test(\"[GET]::/refunds/:id - Content-Type is application/json\", function () {",
+ "pm.test(\"[GET]::/payments/:id - 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(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
"// Set response object as internal variable",
"let jsonData = {};",
"try {",
" jsonData = pm.response.json();",
"} catch (e) {}",
"",
- "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id",
- "if (jsonData?.refund_id) {",
- " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
" console.log(",
- " \"- use {{refund_id}} as collection variable for value\",",
- " jsonData.refund_id,",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
" );",
"} else {",
" console.log(",
- " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
" );",
"}",
"",
- "// Response body should have value \"succeeded\" for \"status\"",
- "if (jsonData?.status) {",
- " pm.test(",
- " \"[POST]::/refunds - Content check if value for 'status' matches 'succeeded'\",",
- " function () {",
- " pm.expect(jsonData.status).to.eql(\"succeeded\");",
- " },",
+ "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
+ "if (jsonData?.mandate_id) {",
+ " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ " console.log(",
+ " \"- use {{mandate_id}} as collection variable for value\",",
+ " jsonData.mandate_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
" );",
"}",
"",
- "// Response body should have value \"6540\" for \"amount\"",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"Succeeded\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/refunds - Content check if value for 'amount' matches '540'\",",
+ " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",",
" function () {",
- " pm.expect(jsonData.amount).to.eql(540);",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
" },",
" );",
"}",
+ "",
+ "// Response body should have \"mandate_id\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_id' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ "",
+ "// Response body should have \"mandate_data\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_data' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;",
+ " },",
+ ");",
""
],
"type": "text/javascript"
@@ -12414,180 +11727,134 @@
}
],
"url": {
- "raw": "{{baseUrl}}/refunds/:id",
+ "raw": "{{baseUrl}}/payments/:id?force_sync=true",
"host": [
"{{baseUrl}}"
],
"path": [
- "refunds",
+ "payments",
":id"
],
+ "query": [
+ {
+ "key": "force_sync",
+ "value": "true"
+ }
+ ],
"variable": [
{
"key": "id",
- "value": "{{refund_id}}",
- "description": "(Required) unique refund id"
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
}
]
},
- "description": "To retrieve the properties of a Refund. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
},
"response": []
},
{
- "name": "Refunds - Create-copy",
+ "name": "Recurring Payments - Create",
"event": [
{
"listen": "test",
"script": {
"exec": [
"// Validate status 2xx",
- "pm.test(\"[POST]::/refunds - Status code is 2xx\", function () {",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
" pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
- "pm.test(\"[POST]::/refunds - Content-Type is application/json\", function () {",
+ "pm.test(\"[POST]::/payments - 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]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
"// Set response object as internal variable",
"let jsonData = {};",
"try {",
" jsonData = pm.response.json();",
"} catch (e) {}",
"",
- "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id",
- "if (jsonData?.refund_id) {",
- " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
" console.log(",
- " \"- use {{refund_id}} as collection variable for value\",",
- " jsonData.refund_id,",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
" );",
"} else {",
" console.log(",
- " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",",
- " );",
- "}",
- "",
- "// Response body should have value \"succeeded\" for \"status\"",
- "if (jsonData?.status) {",
- " pm.test(",
- " \"[POST]::/refunds - Content check if value for 'status' matches 'succeeded'\",",
- " function () {",
- " pm.expect(jsonData.status).to.eql(\"succeeded\");",
- " },",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
" );",
"}",
"",
- "// Response body should have value \"1000\" for \"amount\"",
- "if (jsonData?.status) {",
- " pm.test(",
- " \"[POST]::/refunds - Content check if value for 'amount' matches '1000'\",",
- " function () {",
- " pm.expect(jsonData.amount).to.eql(1000);",
- " },",
+ "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
+ "if (jsonData?.mandate_id) {",
+ " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ " console.log(",
+ " \"- use {{mandate_id}} as collection variable for value\",",
+ " jsonData.mandate_id,",
" );",
- "}",
- ""
- ],
- "type": "text/javascript"
- }
- }
- ],
- "request": {
- "method": "POST",
- "header": [
- {
- "key": "Content-Type",
- "value": "application/json"
- },
- {
- "key": "Accept",
- "value": "application/json"
- }
- ],
- "body": {
- "mode": "raw",
- "options": {
- "raw": {
- "language": "json"
- }
- },
- "raw": "{\"payment_id\":\"{{payment_id}}\",\"amount\":1000,\"reason\":\"Customer returned product\",\"refund_type\":\"instant\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
- },
- "url": {
- "raw": "{{baseUrl}}/refunds",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "refunds"
- ]
- },
- "description": "To create a refund against an already processed payment"
- },
- "response": []
- },
- {
- "name": "Refunds - Retrieve-copy",
- "event": [
- {
- "listen": "test",
- "script": {
- "exec": [
- "// Validate status 2xx",
- "pm.test(\"[GET]::/refunds/:id - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
- "});",
- "",
- "// Validate if response header has matching content-type",
- "pm.test(\"[GET]::/refunds/:id - Content-Type is application/json\", function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
- " \"application/json\",",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
" );",
- "});",
- "",
- "// Set response object as internal variable",
- "let jsonData = {};",
- "try {",
- " jsonData = pm.response.json();",
- "} catch (e) {}",
+ "}",
"",
- "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id",
- "if (jsonData?.refund_id) {",
- " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
" console.log(",
- " \"- use {{refund_id}} as collection variable for value\",",
- " jsonData.refund_id,",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
" );",
"} else {",
" console.log(",
- " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
" );",
"}",
"",
"// Response body should have value \"succeeded\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/refunds - Content check if value for 'status' matches 'succeeded'\",",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",",
" function () {",
" pm.expect(jsonData.status).to.eql(\"succeeded\");",
" },",
" );",
"}",
"",
- "// Response body should have value \"6540\" for \"amount\"",
- "if (jsonData?.status) {",
- " pm.test(",
- " \"[POST]::/refunds - Content check if value for 'amount' matches '1000'\",",
- " function () {",
- " pm.expect(jsonData.amount).to.eql(1000);",
- " },",
- " );",
- "}",
+ "// Response body should have \"mandate_id\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_id' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ "",
+ "// Response body should have \"mandate_data\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_data' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ "",
+ "// Response body should have \"payment_method_data\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'payment_method_data' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.payment_method_data !== \"undefined\").to.be.true;",
+ " },",
+ ");",
""
],
"type": "text/javascript"
@@ -12595,31 +11862,36 @@
}
],
"request": {
- "method": "GET",
+ "method": "POST",
"header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
{
"key": "Accept",
"value": "application/json"
}
],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":6540,\"currency\":\"USD\",\"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\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"mandate_id\":\"{{mandate_id}}\",\"off_session\":true,\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"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}}/refunds/:id",
+ "raw": "{{baseUrl}}/payments",
"host": [
"{{baseUrl}}"
],
"path": [
- "refunds",
- ":id"
- ],
- "variable": [
- {
- "key": "id",
- "value": "{{refund_id}}",
- "description": "(Required) unique refund id"
- }
+ "payments"
]
},
- "description": "To retrieve the properties of a Refund. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
},
"response": []
},
@@ -12702,10 +11974,21 @@
" );",
"}",
"",
- "// Response body should have \"refunds\"",
- "pm.test(\"[POST]::/payments - Content check if 'refunds' exists\", function () {",
- " pm.expect(typeof jsonData.refunds !== \"undefined\").to.be.true;",
- "});",
+ "// Response body should have \"mandate_id\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_id' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ "",
+ "// Response body should have \"mandate_data\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'mandate_data' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;",
+ " },",
+ ");",
""
],
"type": "text/javascript"
@@ -12750,7 +12033,7 @@
]
},
{
- "name": "Scenario10-Create a mandate and recurring payment",
+ "name": "Scenario11-Refund recurring payment",
"item": [
{
"name": "Payments - Create",
@@ -12881,7 +12164,7 @@
"language": "json"
}
},
- "raw": "{\"amount\":6540,\"currency\":\"USD\",\"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\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"setup_future_usage\":\"off_session\",\"mandate_data\":{\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"127.0.0.1\",\"user_agent\":\"amet irure esse\"}},\"mandate_type\":{\"single_use\":{\"amount\":7000,\"currency\":\"USD\"}}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"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\":6540,\"currency\":\"USD\",\"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\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"setup_future_usage\":\"off_session\",\"mandate_data\":{\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"127.0.0.1\",\"user_agent\":\"amet irure esse\"}},\"mandate_type\":{\"single_use\":{\"amount\":7000,\"currency\":\"USD\"}}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"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",
@@ -13110,6 +12393,16 @@
" );",
"}",
"",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ "",
"// Response body should have \"mandate_id\"",
"pm.test(",
" \"[POST]::/payments - Content check if 'mandate_id' exists\",",
@@ -13158,7 +12451,7 @@
"language": "json"
}
},
- "raw": "{\"amount\":6540,\"currency\":\"USD\",\"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\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"mandate_id\":\"{{mandate_id}}\",\"off_session\":true,\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"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\":6570,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6570,\"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://duck.com\",\"mandate_id\":\"{{mandate_id}}\",\"off_session\":true,\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"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",
@@ -13307,116 +12600,64 @@
"description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
},
"response": []
- }
- ]
- },
- {
- "name": "Scenario11-Refund recurring payment",
- "item": [
+ },
{
- "name": "Payments - Create",
+ "name": "Refunds - Create Copy",
"event": [
{
"listen": "test",
"script": {
"exec": [
"// Validate status 2xx",
- "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ "pm.test(\"[POST]::/refunds - Status code is 2xx\", function () {",
" pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
- "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ "pm.test(\"[POST]::/refunds - 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]::/payments - Response has JSON Body\", function () {",
- " pm.response.to.have.jsonBody();",
- "});",
- "",
"// Set response object as internal variable",
"let jsonData = {};",
"try {",
" jsonData = pm.response.json();",
"} catch (e) {}",
"",
- "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
- "if (jsonData?.payment_id) {",
- " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
- " console.log(",
- " \"- use {{payment_id}} as collection variable for value\",",
- " jsonData.payment_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
- " );",
- "}",
- "",
- "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
- "if (jsonData?.mandate_id) {",
- " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
- " console.log(",
- " \"- use {{mandate_id}} as collection variable for value\",",
- " jsonData.mandate_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
- " );",
- "}",
- "",
- "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
- "if (jsonData?.client_secret) {",
- " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id",
+ "if (jsonData?.refund_id) {",
+ " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);",
" console.log(",
- " \"- use {{client_secret}} as collection variable for value\",",
- " jsonData.client_secret,",
+ " \"- use {{refund_id}} as collection variable for value\",",
+ " jsonData.refund_id,",
" );",
"} else {",
" console.log(",
- " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",",
" );",
"}",
"",
"// Response body should have value \"succeeded\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",",
+ " \"[POST]::/refunds - Content check if value for 'status' matches 'succeeded'\",",
" function () {",
" pm.expect(jsonData.status).to.eql(\"succeeded\");",
" },",
" );",
"}",
"",
- "// Response body should have value \"succeeded\" for \"status\"",
+ "// Response body should have value \"6540\" for \"amount\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",",
+ " \"[POST]::/refunds - Content check if value for 'amount' matches '6540'\",",
" function () {",
- " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " pm.expect(jsonData.amount).to.eql(6540);",
" },",
" );",
"}",
- "",
- "// Response body should have \"mandate_id\"",
- "pm.test(",
- " \"[POST]::/payments - Content check if 'mandate_id' exists\",",
- " function () {",
- " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;",
- " },",
- ");",
- "",
- "// Response body should have \"mandate_data\"",
- "pm.test(",
- " \"[POST]::/payments - Content check if 'mandate_data' exists\",",
- " function () {",
- " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;",
- " },",
- ");",
""
],
"type": "text/javascript"
@@ -13442,115 +12683,78 @@
"language": "json"
}
},
- "raw": "{\"amount\":6540,\"currency\":\"USD\",\"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\":\"+65\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"setup_future_usage\":\"off_session\",\"mandate_data\":{\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"127.0.0.1\",\"user_agent\":\"amet irure esse\"}},\"mandate_type\":{\"single_use\":{\"amount\":7000,\"currency\":\"USD\"}}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"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": "{\"payment_id\":\"{{payment_id}}\",\"amount\":6540,\"reason\":\"Customer returned product\",\"refund_type\":\"instant\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
},
"url": {
- "raw": "{{baseUrl}}/payments",
+ "raw": "{{baseUrl}}/refunds",
"host": [
"{{baseUrl}}"
],
"path": [
- "payments"
+ "refunds"
]
},
- "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ "description": "To create a refund against an already processed payment"
},
"response": []
},
{
- "name": "Payments - Retrieve",
+ "name": "Refunds - Retrieve Copy",
"event": [
{
"listen": "test",
"script": {
"exec": [
"// Validate status 2xx",
- "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
+ "pm.test(\"[GET]::/refunds/:id - Status code is 2xx\", function () {",
" pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
- "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {",
+ "pm.test(\"[GET]::/refunds/:id - 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(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
- " pm.response.to.have.jsonBody();",
- "});",
- "",
"// Set response object as internal variable",
"let jsonData = {};",
"try {",
" jsonData = pm.response.json();",
"} catch (e) {}",
"",
- "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
- "if (jsonData?.payment_id) {",
- " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
- " console.log(",
- " \"- use {{payment_id}} as collection variable for value\",",
- " jsonData.payment_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
- " );",
- "}",
- "",
- "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
- "if (jsonData?.mandate_id) {",
- " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id",
+ "if (jsonData?.refund_id) {",
+ " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);",
" console.log(",
- " \"- use {{mandate_id}} as collection variable for value\",",
- " jsonData.mandate_id,",
+ " \"- use {{refund_id}} as collection variable for value\",",
+ " jsonData.refund_id,",
" );",
"} else {",
" console.log(",
- " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
+ " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",",
" );",
"}",
"",
- "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
- "if (jsonData?.client_secret) {",
- " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
- " console.log(",
- " \"- use {{client_secret}} as collection variable for value\",",
- " jsonData.client_secret,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/refunds - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
" );",
"}",
"",
- "// Response body should have value \"Succeeded\" for \"status\"",
+ "// Response body should have value \"6540\" for \"amount\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",",
+ " \"[POST]::/refunds - Content check if value for 'amount' matches '6540'\",",
" function () {",
- " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " pm.expect(jsonData.amount).to.eql(6540);",
" },",
" );",
"}",
- "",
- "// Response body should have \"mandate_id\"",
- "pm.test(",
- " \"[POST]::/payments - Content check if 'mandate_id' exists\",",
- " function () {",
- " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;",
- " },",
- ");",
- "",
- "// Response body should have \"mandate_data\"",
- "pm.test(",
- " \"[POST]::/payments - Content check if 'mandate_data' exists\",",
- " function () {",
- " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;",
- " },",
- ");",
""
],
"type": "text/javascript"
@@ -13566,34 +12770,33 @@
}
],
"url": {
- "raw": "{{baseUrl}}/payments/:id?force_sync=true",
+ "raw": "{{baseUrl}}/refunds/:id",
"host": [
"{{baseUrl}}"
],
"path": [
- "payments",
+ "refunds",
":id"
],
- "query": [
- {
- "key": "force_sync",
- "value": "true"
- }
- ],
"variable": [
{
"key": "id",
- "value": "{{payment_id}}",
- "description": "(Required) unique payment id"
+ "value": "{{refund_id}}",
+ "description": "(Required) unique refund id"
}
]
},
- "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ "description": "To retrieve the properties of a Refund. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
},
"response": []
- },
+ }
+ ]
+ },
+ {
+ "name": "Scenario12-BNPL-klarna",
+ "item": [
{
- "name": "Recurring Payments - Create",
+ "name": "Payments - Create",
"event": [
{
"listen": "test",
@@ -13661,49 +12864,15 @@
" );",
"}",
"",
- "// Response body should have value \"succeeded\" for \"status\"",
- "if (jsonData?.status) {",
- " pm.test(",
- " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",",
- " function () {",
- " pm.expect(jsonData.status).to.eql(\"succeeded\");",
- " },",
- " );",
- "}",
- "",
- "// Response body should have value \"succeeded\" for \"status\"",
+ "// Response body should have value \"requires_payment_method\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'\",",
" function () {",
- " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " pm.expect(jsonData.status).to.eql(\"requires_payment_method\");",
" },",
" );",
"}",
- "",
- "// Response body should have \"mandate_id\"",
- "pm.test(",
- " \"[POST]::/payments - Content check if 'mandate_id' exists\",",
- " function () {",
- " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;",
- " },",
- ");",
- "",
- "// Response body should have \"mandate_data\"",
- "pm.test(",
- " \"[POST]::/payments - Content check if 'mandate_data' exists\",",
- " function () {",
- " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;",
- " },",
- ");",
- "",
- "// Response body should have \"payment_method_data\"",
- "pm.test(",
- " \"[POST]::/payments - Content check if 'payment_method_data' exists\",",
- " function () {",
- " pm.expect(typeof jsonData.payment_method_data !== \"undefined\").to.be.true;",
- " },",
- ");",
""
],
"type": "text/javascript"
@@ -13729,7 +12898,7 @@
"language": "json"
}
},
- "raw": "{\"amount\":6570,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6570,\"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://duck.com\",\"mandate_id\":\"{{mandate_id}}\",\"off_session\":true,\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"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\":8000,\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":8000,\"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://duck.com\",\"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",
@@ -13745,26 +12914,29 @@
"response": []
},
{
- "name": "Payments - Retrieve-copy",
+ "name": "Payments - Confirm",
"event": [
{
"listen": "test",
"script": {
"exec": [
"// Validate status 2xx",
- "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
+ "pm.test(\"[POST]::/payments/:id/confirm - Status code is 2xx\", function () {",
" pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
- "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
- " \"application/json\",",
- " );",
- "});",
+ "pm.test(",
+ " \"[POST]::/payments/:id/confirm - 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(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
+ "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {",
" pm.response.to.have.jsonBody();",
"});",
"",
@@ -13813,31 +12985,53 @@
" );",
"}",
"",
- "// Response body should have value \"Succeeded\" for \"status\"",
+ "// Response body should have value \"requires_customer_action\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",",
+ " \"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'requires_customer_action'\",",
" function () {",
- " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");",
" },",
" );",
"}",
"",
- "// Response body should have \"mandate_id\"",
+ "// Response body should have \"next_action.redirect_to_url\"",
"pm.test(",
- " \"[POST]::/payments - Content check if 'mandate_id' exists\",",
+ " \"[POST]::/payments - Content check if 'next_action.redirect_to_url' exists\",",
" function () {",
- " pm.expect(typeof jsonData.mandate_id !== \"undefined\").to.be.true;",
+ " pm.expect(typeof jsonData.next_action.redirect_to_url !== \"undefined\").to.be",
+ " .true;",
" },",
");",
"",
- "// Response body should have \"mandate_data\"",
- "pm.test(",
- " \"[POST]::/payments - Content check if 'mandate_data' exists\",",
- " function () {",
- " pm.expect(typeof jsonData.mandate_data !== \"undefined\").to.be.true;",
- " },",
- ");",
+ "// Response body should have value \"klarna\" for \"payment_method_type\"",
+ "if (jsonData?.payment_method_type) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id/confirm - Content check if value for 'payment_method_type' matches 'klarna'\",",
+ " function () {",
+ " pm.expect(jsonData.payment_method_type).to.eql(\"klarna\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"stripe\" for \"connector\"",
+ "if (jsonData?.connector) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id/confirm - Content check if value for 'connector' matches 'stripe'\",",
+ " function () {",
+ " pm.expect(jsonData.connector).to.eql(\"stripe\");",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ },
+ {
+ "listen": "prerequest",
+ "script": {
+ "exec": [
""
],
"type": "text/javascript"
@@ -13845,27 +13039,55 @@
}
],
"request": {
- "method": "GET",
+ "auth": {
+ "type": "apikey",
+ "apikey": [
+ {
+ "key": "value",
+ "value": "{{publishable_key}}",
+ "type": "string"
+ },
+ {
+ "key": "key",
+ "value": "api-key",
+ "type": "string"
+ },
+ {
+ "key": "in",
+ "value": "header",
+ "type": "string"
+ }
+ ]
+ },
+ "method": "POST",
"header": [
{
- "key": "Accept",
+ "key": "Content-Type",
"value": "application/json"
- }
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"payment_method\":\"pay_later\",\"payment_method_type\":\"klarna\",\"payment_experience\":\"redirect_to_url\",\"payment_method_data\":{\"pay_later\":{\"klarna_redirect\":{\"issuer_name\":\"stripe\",\"billing_email\":\"arjun.karthik@juspay.in\",\"billing_country\":\"US\"}}},\"client_secret\":\"{{client_secret}}\"}"
+ },
"url": {
- "raw": "{{baseUrl}}/payments/:id?force_sync=true",
+ "raw": "{{baseUrl}}/payments/:id/confirm",
"host": [
"{{baseUrl}}"
],
"path": [
"payments",
- ":id"
- ],
- "query": [
- {
- "key": "force_sync",
- "value": "true"
- }
+ ":id",
+ "confirm"
],
"variable": [
{
@@ -13875,161 +13097,85 @@
}
]
},
- "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API"
},
"response": []
},
{
- "name": "Refunds - Create Copy",
+ "name": "Payments - Retrieve",
"event": [
{
"listen": "test",
"script": {
"exec": [
"// Validate status 2xx",
- "pm.test(\"[POST]::/refunds - Status code is 2xx\", function () {",
+ "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
" pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
- "pm.test(\"[POST]::/refunds - Content-Type is application/json\", function () {",
+ "pm.test(\"[GET]::/payments/:id - 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(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
"// Set response object as internal variable",
"let jsonData = {};",
"try {",
" jsonData = pm.response.json();",
"} catch (e) {}",
"",
- "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id",
- "if (jsonData?.refund_id) {",
- " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
" console.log(",
- " \"- use {{refund_id}} as collection variable for value\",",
- " jsonData.refund_id,",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
" );",
"} else {",
" console.log(",
- " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
" );",
"}",
"",
- "// Response body should have value \"succeeded\" for \"status\"",
- "if (jsonData?.status) {",
- " pm.test(",
- " \"[POST]::/refunds - Content check if value for 'status' matches 'succeeded'\",",
- " function () {",
- " pm.expect(jsonData.status).to.eql(\"succeeded\");",
- " },",
+ "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
+ "if (jsonData?.mandate_id) {",
+ " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ " console.log(",
+ " \"- use {{mandate_id}} as collection variable for value\",",
+ " jsonData.mandate_id,",
" );",
- "}",
- "",
- "// Response body should have value \"6540\" for \"amount\"",
- "if (jsonData?.status) {",
- " pm.test(",
- " \"[POST]::/refunds - Content check if value for 'amount' matches '6540'\",",
- " function () {",
- " pm.expect(jsonData.amount).to.eql(6540);",
- " },",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
" );",
"}",
- ""
- ],
- "type": "text/javascript"
- }
- }
- ],
- "request": {
- "method": "POST",
- "header": [
- {
- "key": "Content-Type",
- "value": "application/json"
- },
- {
- "key": "Accept",
- "value": "application/json"
- }
- ],
- "body": {
- "mode": "raw",
- "options": {
- "raw": {
- "language": "json"
- }
- },
- "raw": "{\"payment_id\":\"{{payment_id}}\",\"amount\":6540,\"reason\":\"Customer returned product\",\"refund_type\":\"instant\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
- },
- "url": {
- "raw": "{{baseUrl}}/refunds",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "refunds"
- ]
- },
- "description": "To create a refund against an already processed payment"
- },
- "response": []
- },
- {
- "name": "Refunds - Retrieve Copy",
- "event": [
- {
- "listen": "test",
- "script": {
- "exec": [
- "// Validate status 2xx",
- "pm.test(\"[GET]::/refunds/:id - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
- "});",
- "",
- "// Validate if response header has matching content-type",
- "pm.test(\"[GET]::/refunds/:id - Content-Type is application/json\", function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
- " \"application/json\",",
- " );",
- "});",
- "",
- "// Set response object as internal variable",
- "let jsonData = {};",
- "try {",
- " jsonData = pm.response.json();",
- "} catch (e) {}",
"",
- "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id",
- "if (jsonData?.refund_id) {",
- " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
" console.log(",
- " \"- use {{refund_id}} as collection variable for value\",",
- " jsonData.refund_id,",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
" );",
"} else {",
" console.log(",
- " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",",
- " );",
- "}",
- "",
- "// Response body should have value \"succeeded\" for \"status\"",
- "if (jsonData?.status) {",
- " pm.test(",
- " \"[POST]::/refunds - Content check if value for 'status' matches 'succeeded'\",",
- " function () {",
- " pm.expect(jsonData.status).to.eql(\"succeeded\");",
- " },",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
" );",
"}",
"",
- "// Response body should have value \"6540\" for \"amount\"",
+ "// Response body should have value \"requires_customer_action\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/refunds - Content check if value for 'amount' matches '6540'\",",
+ " \"[POST]::/payments:id - Content check if value for 'status' matches 'requires_customer_action'\",",
" function () {",
- " pm.expect(jsonData.amount).to.eql(6540);",
+ " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");",
" },",
" );",
"}",
@@ -14048,30 +13194,36 @@
}
],
"url": {
- "raw": "{{baseUrl}}/refunds/:id",
+ "raw": "{{baseUrl}}/payments/:id?force_sync=true",
"host": [
"{{baseUrl}}"
],
"path": [
- "refunds",
+ "payments",
":id"
],
+ "query": [
+ {
+ "key": "force_sync",
+ "value": "true"
+ }
+ ],
"variable": [
{
"key": "id",
- "value": "{{refund_id}}",
- "description": "(Required) unique refund id"
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
}
]
},
- "description": "To retrieve the properties of a Refund. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
},
"response": []
}
]
},
{
- "name": "Scenario12-BNPL-klarna",
+ "name": "Scenario13-BNPL-afterpay",
"item": [
{
"name": "Payments - Create",
@@ -14176,7 +13328,7 @@
"language": "json"
}
},
- "raw": "{\"amount\":8000,\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":8000,\"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://duck.com\",\"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\":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\"}},\"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",
@@ -14282,12 +13434,12 @@
" },",
");",
"",
- "// Response body should have value \"klarna\" for \"payment_method_type\"",
+ "// Response body should have value \"afterpay_clearpay\" for \"payment_method_type\"",
"if (jsonData?.payment_method_type) {",
" pm.test(",
- " \"[POST]::/payments/:id/confirm - Content check if value for 'payment_method_type' matches 'klarna'\",",
+ " \"[POST]::/payments/:id/confirm - Content check if value for 'payment_method_type' matches 'afterpay_clearpay'\",",
" function () {",
- " pm.expect(jsonData.payment_method_type).to.eql(\"klarna\");",
+ " pm.expect(jsonData.payment_method_type).to.eql(\"afterpay_clearpay\");",
" },",
" );",
"}",
@@ -14355,7 +13507,7 @@
"language": "json"
}
},
- "raw": "{\"payment_method\":\"pay_later\",\"payment_method_type\":\"klarna\",\"payment_experience\":\"redirect_to_url\",\"payment_method_data\":{\"pay_later\":{\"klarna_redirect\":{\"issuer_name\":\"stripe\",\"billing_email\":\"arjun.karthik@juspay.in\",\"billing_country\":\"US\"}}},\"client_secret\":\"{{client_secret}}\"}"
+ "raw": "{\"payment_method\":\"pay_later\",\"payment_method_type\":\"afterpay_clearpay\",\"payment_experience\":\"redirect_to_url\",\"payment_method_data\":{\"pay_later\":{\"afterpay_clearpay_redirect\":{\"billing_name\":\"Akshaya\",\"billing_email\":\"example@example.com\"}}},\"client_secret\":\"{{client_secret}}\"}"
},
"url": {
"raw": "{{baseUrl}}/payments/:id/confirm",
@@ -14501,7 +13653,7 @@
]
},
{
- "name": "Scenario13-BNPL-afterpay",
+ "name": "Scenario14-BNPL-affirm",
"item": [
{
"name": "Payments - Create",
@@ -14606,7 +13758,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\"}},\"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\":\"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\"},\"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\":{\"order_details\":{\"product_name\":\"Socks\",\"amount\":7000,\"quantity\":1}},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}"
},
"url": {
"raw": "{{baseUrl}}/payments",
@@ -14712,12 +13864,12 @@
" },",
");",
"",
- "// Response body should have value \"afterpay_clearpay\" for \"payment_method_type\"",
+ "// Response body should have value \"affirm\" for \"payment_method_type\"",
"if (jsonData?.payment_method_type) {",
" pm.test(",
- " \"[POST]::/payments/:id/confirm - Content check if value for 'payment_method_type' matches 'afterpay_clearpay'\",",
+ " \"[POST]::/payments/:id/confirm - Content check if value for 'payment_method_type' matches 'affirm'\",",
" function () {",
- " pm.expect(jsonData.payment_method_type).to.eql(\"afterpay_clearpay\");",
+ " pm.expect(jsonData.payment_method_type).to.eql(\"affirm\");",
" },",
" );",
"}",
@@ -14785,7 +13937,7 @@
"language": "json"
}
},
- "raw": "{\"payment_method\":\"pay_later\",\"payment_method_type\":\"afterpay_clearpay\",\"payment_experience\":\"redirect_to_url\",\"payment_method_data\":{\"pay_later\":{\"afterpay_clearpay_redirect\":{\"billing_name\":\"Akshaya\",\"billing_email\":\"example@example.com\"}}},\"client_secret\":\"{{client_secret}}\"}"
+ "raw": "{\"payment_method\":\"pay_later\",\"payment_method_type\":\"affirm\",\"payment_experience\":\"redirect_to_url\",\"payment_method_data\":{\"pay_later\":{\"affirm_redirect\":{\"issuer_name\":\"affirm\",\"billing_email\":\"user-us@example.com\",\"billing_country\":\"US\"}}},\"client_secret\":\"{{client_secret}}\"}"
},
"url": {
"raw": "{{baseUrl}}/payments/:id/confirm",
@@ -14931,7 +14083,7 @@
]
},
{
- "name": "Scenario14-BNPL-affirm",
+ "name": "Scenario15-Bank Redirect-Ideal",
"item": [
{
"name": "Payments - Create",
@@ -15036,7 +14188,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\":\"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\"},\"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\":{\"order_details\":{\"product_name\":\"Socks\",\"amount\":7000,\"quantity\":1}},\"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\":\"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\"}}"
},
"url": {
"raw": "{{baseUrl}}/payments",
@@ -15142,12 +14294,12 @@
" },",
");",
"",
- "// Response body should have value \"affirm\" for \"payment_method_type\"",
+ "// Response body should have value \"ideal\" for \"payment_method_type\"",
"if (jsonData?.payment_method_type) {",
" pm.test(",
- " \"[POST]::/payments/:id/confirm - Content check if value for 'payment_method_type' matches 'affirm'\",",
+ " \"[POST]::/payments/:id/confirm - Content check if value for 'payment_method_type' matches 'ideal'\",",
" function () {",
- " pm.expect(jsonData.payment_method_type).to.eql(\"affirm\");",
+ " pm.expect(jsonData.payment_method_type).to.eql(\"ideal\");",
" },",
" );",
"}",
@@ -15215,7 +14367,7 @@
"language": "json"
}
},
- "raw": "{\"payment_method\":\"pay_later\",\"payment_method_type\":\"affirm\",\"payment_experience\":\"redirect_to_url\",\"payment_method_data\":{\"pay_later\":{\"affirm_redirect\":{\"issuer_name\":\"affirm\",\"billing_email\":\"user-us@example.com\",\"billing_country\":\"US\"}}},\"client_secret\":\"{{client_secret}}\"}"
+ "raw": "{\"payment_method\":\"bank_redirect\",\"payment_method_type\":\"ideal\",\"payment_method_data\":{\"bank_redirect\":{\"ideal\":{\"billing_details\":{\"billing_name\":\"John Doe\"},\"bank_name\":\"ing\",\"preferred_language\":\"en\",\"country\":\"DE\"}}},\"client_secret\":\"{{client_secret}}\"}"
},
"url": {
"raw": "{{baseUrl}}/payments/:id/confirm",
@@ -15361,7 +14513,7 @@
]
},
{
- "name": "Scenario15-Bank Redirect-Ideal",
+ "name": "Scenario16-Bank Redirect-sofort",
"item": [
{
"name": "Payments - Create",
@@ -15572,12 +14724,12 @@
" },",
");",
"",
- "// Response body should have value \"ideal\" for \"payment_method_type\"",
+ "// Response body should have value \"sofort\" for \"payment_method_type\"",
"if (jsonData?.payment_method_type) {",
" pm.test(",
- " \"[POST]::/payments/:id/confirm - Content check if value for 'payment_method_type' matches 'ideal'\",",
+ " \"[POST]::/payments/:id/confirm - Content check if value for 'payment_method_type' matches 'sofort'\",",
" function () {",
- " pm.expect(jsonData.payment_method_type).to.eql(\"ideal\");",
+ " pm.expect(jsonData.payment_method_type).to.eql(\"sofort\");",
" },",
" );",
"}",
@@ -15645,7 +14797,7 @@
"language": "json"
}
},
- "raw": "{\"payment_method\":\"bank_redirect\",\"payment_method_type\":\"ideal\",\"payment_method_data\":{\"bank_redirect\":{\"ideal\":{\"billing_details\":{\"billing_name\":\"John Doe\"},\"bank_name\":\"ing\",\"preferred_language\":\"en\",\"country\":\"DE\"}}},\"client_secret\":\"{{client_secret}}\"}"
+ "raw": "{\"payment_method\":\"bank_redirect\",\"payment_method_type\":\"sofort\",\"payment_method_data\":{\"bank_redirect\":{\"sofort\":{\"billing_details\":{\"billing_name\":\"John Doe\"},\"bank_name\":\"hypo_noe_lb_fur_niederosterreich_u_wien\",\"preferred_language\":\"en\",\"country\":\"DE\"}}},\"client_secret\":\"{{client_secret}}\"}"
},
"url": {
"raw": "{{baseUrl}}/payments/:id/confirm",
@@ -15791,7 +14943,7 @@
]
},
{
- "name": "Scenario16-Bank Redirect-sofort",
+ "name": "Scenario17-Bank Redirect-eps",
"item": [
{
"name": "Payments - Create",
@@ -16002,12 +15154,12 @@
" },",
");",
"",
- "// Response body should have value \"sofort\" for \"payment_method_type\"",
+ "// Response body should have value \"eps\" for \"payment_method_type\"",
"if (jsonData?.payment_method_type) {",
" pm.test(",
- " \"[POST]::/payments/:id/confirm - Content check if value for 'payment_method_type' matches 'sofort'\",",
+ " \"[POST]::/payments/:id/confirm - Content check if value for 'payment_method_type' matches 'eps'\",",
" function () {",
- " pm.expect(jsonData.payment_method_type).to.eql(\"sofort\");",
+ " pm.expect(jsonData.payment_method_type).to.eql(\"eps\");",
" },",
" );",
"}",
@@ -16075,7 +15227,7 @@
"language": "json"
}
},
- "raw": "{\"payment_method\":\"bank_redirect\",\"payment_method_type\":\"sofort\",\"payment_method_data\":{\"bank_redirect\":{\"sofort\":{\"billing_details\":{\"billing_name\":\"John Doe\"},\"bank_name\":\"hypo_noe_lb_fur_niederosterreich_u_wien\",\"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\":\"DE\"}}},\"client_secret\":\"{{client_secret}}\"}"
},
"url": {
"raw": "{{baseUrl}}/payments/:id/confirm",
@@ -16221,7 +15373,7 @@
]
},
{
- "name": "Scenario17-Bank Redirect-eps",
+ "name": "Scenario18-Bank Redirect-giropay",
"item": [
{
"name": "Payments - Create",
@@ -16432,12 +15584,12 @@
" },",
");",
"",
- "// Response body should have value \"eps\" for \"payment_method_type\"",
+ "// Response body should have value \"giropay\" for \"payment_method_type\"",
"if (jsonData?.payment_method_type) {",
" pm.test(",
- " \"[POST]::/payments/:id/confirm - Content check if value for 'payment_method_type' matches 'eps'\",",
+ " \"[POST]::/payments/:id/confirm - Content check if value for 'payment_method_type' matches 'giropay'\",",
" function () {",
- " pm.expect(jsonData.payment_method_type).to.eql(\"eps\");",
+ " pm.expect(jsonData.payment_method_type).to.eql(\"giropay\");",
" },",
" );",
"}",
@@ -16505,7 +15657,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\":\"giropay\",\"payment_method_data\":{\"bank_redirect\":{\"giropay\":{\"billing_details\":{\"billing_name\":\"John Doe\"},\"bank_name\":\"\",\"preferred_language\":\"en\",\"country\":\"DE\"}}},\"client_secret\":\"{{client_secret}}\"}"
},
"url": {
"raw": "{{baseUrl}}/payments/:id/confirm",
@@ -16651,7 +15803,7 @@
]
},
{
- "name": "Scenario18-Bank Redirect-giropay",
+ "name": "Scenario19-Bank Transfer-ach",
"item": [
{
"name": "Payments - Create",
@@ -16756,7 +15908,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\":800,\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":800,\"customer_id\":\"poll\",\"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://hs-payments-test.netlify.app/payments\",\"statement_descriptor_name\":\"Juspay\",\"statement_descriptor_suffix\":\"Router\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}"
},
"url": {
"raw": "{{baseUrl}}/payments",
@@ -16853,21 +16005,32 @@
" );",
"}",
"",
- "// Response body should have \"next_action.redirect_to_url\"",
+ "// Response body should have \"next_action.type\"",
"pm.test(",
- " \"[POST]::/payments - Content check if 'next_action.redirect_to_url' exists\",",
+ " \"[POST]::/payments - Content check if 'next_action.type' exists\",",
" function () {",
- " pm.expect(typeof jsonData.next_action.redirect_to_url !== \"undefined\").to.be",
- " .true;",
+ " pm.expect(typeof jsonData.next_action.type !== \"undefined\").to.be.true;",
" },",
");",
"",
- "// Response body should have value \"giropay\" for \"payment_method_type\"",
+ "// Response body should have value \"ach\" for \"payment_method_type\"",
"if (jsonData?.payment_method_type) {",
" pm.test(",
- " \"[POST]::/payments/:id/confirm - Content check if value for 'payment_method_type' matches 'giropay'\",",
+ " \"[POST]::/payments/:id/confirm - Content check if value for 'payment_method_type' matches 'ach'\",",
" function () {",
- " pm.expect(jsonData.payment_method_type).to.eql(\"giropay\");",
+ " pm.expect(jsonData.payment_method_type).to.eql(\"ach\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"display_bank_transfer_information\" for \"next_action.type\"",
+ "if (jsonData?.next_action.type) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id/confirm - Content check if value for 'payment_method_type' matches 'display_bank_transfer_information'\",",
+ " function () {",
+ " pm.expect(jsonData.next_action.type).to.eql(",
+ " \"display_bank_transfer_information\",",
+ " );",
" },",
" );",
"}",
@@ -16935,7 +16098,7 @@
"language": "json"
}
},
- "raw": "{\"payment_method\":\"bank_redirect\",\"payment_method_type\":\"giropay\",\"payment_method_data\":{\"bank_redirect\":{\"giropay\":{\"billing_details\":{\"billing_name\":\"John Doe\"},\"bank_name\":\"\",\"preferred_language\":\"en\",\"country\":\"DE\"}}},\"client_secret\":\"{{client_secret}}\"}"
+ "raw": "{\"payment_method\":\"bank_transfer\",\"payment_method_type\":\"ach\",\"payment_method_data\":{\"bank_transfer\":{\"ach_bank_transfer\":{\"billing_details\":{\"email\":\"johndoe@example.com\"}}}},\"client_secret\":\"{{client_secret}}\"}"
},
"url": {
"raw": "{{baseUrl}}/payments/:id/confirm",
@@ -17081,7 +16244,7 @@
]
},
{
- "name": "Scenario19-Bank Transfer-ach",
+ "name": "Scenario20-Bank Debit-ach",
"item": [
{
"name": "Payments - Create",
@@ -17152,12 +16315,12 @@
" );",
"}",
"",
- "// Response body should have value \"requires_payment_method\" for \"status\"",
+ "// Response body should have value \"requires_customer_action\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'\",",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'requires_customer_action'\",",
" function () {",
- " pm.expect(jsonData.status).to.eql(\"requires_payment_method\");",
+ " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");",
" },",
" );",
"}",
@@ -17165,6 +16328,15 @@
],
"type": "text/javascript"
}
+ },
+ {
+ "listen": "prerequest",
+ "script": {
+ "exec": [
+ ""
+ ],
+ "type": "text/javascript"
+ }
}
],
"request": {
@@ -17186,7 +16358,7 @@
"language": "json"
}
},
- "raw": "{\"amount\":800,\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":800,\"customer_id\":\"poll\",\"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://hs-payments-test.netlify.app/payments\",\"statement_descriptor_name\":\"Juspay\",\"statement_descriptor_suffix\":\"Router\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}"
+ "raw": "{\"amount\":1800,\"currency\":\"USD\",\"confirm\":true,\"business_label\":\"default\",\"capture_method\":\"automatic\",\"connector\":[\"stripe\"],\"customer_id\":\"klarna\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"authentication_type\":\"three_ds\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"return_url\":\"https://google.com\",\"statement_descriptor_name\":\"Juspay\",\"statement_descriptor_suffix\":\"Router\",\"setup_future_usage\":\"off_session\",\"business_country\":\"US\",\"mandate_data\":{\"customer_acceptance\":{\"acceptance_type\":\"online\",\"accepted_at\":\"2022-09-10T10:11:12Z\",\"online\":{\"ip_address\":\"123.32.25.123\",\"user_agent\":\"Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36\"}},\"mandate_type\":{\"single_use\":{\"amount\":6540,\"currency\":\"USD\"}}},\"payment_method\":\"bank_debit\",\"payment_method_type\":\"ach\",\"payment_method_data\":{\"bank_debit\":{\"ach_bank_debit\":{\"billing_details\":{\"name\":\"John Doe\",\"email\":\"johndoe@example.com\"},\"account_number\":\"000123456789\",\"routing_number\":\"110000000\"}}},\"metadata\":{\"order_details\":{\"product_name\":\"Apple iphone 15\",\"quantity\":1,\"amount\":1800,\"account_name\":\"transaction_processing\"}},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}"
},
"url": {
"raw": "{{baseUrl}}/payments",
@@ -17202,29 +16374,26 @@
"response": []
},
{
- "name": "Payments - Confirm",
+ "name": "Payments - Retrieve",
"event": [
{
"listen": "test",
"script": {
"exec": [
"// Validate status 2xx",
- "pm.test(\"[POST]::/payments/:id/confirm - Status code is 2xx\", function () {",
+ "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
" pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
- "pm.test(",
- " \"[POST]::/payments/:id/confirm - Content-Type is application/json\",",
- " function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
- " \"application/json\",",
- " );",
- " },",
- ");",
+ "pm.test(\"[GET]::/payments/:id - 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]::/payments/:id/confirm - Response has JSON Body\", function () {",
+ "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
" pm.response.to.have.jsonBody();",
"});",
"",
@@ -17276,61 +16445,12 @@
"// Response body should have value \"requires_customer_action\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'requires_customer_action'\",",
+ " \"[POST]::/payments:id - Content check if value for 'status' matches 'requires_customer_action'\",",
" function () {",
" pm.expect(jsonData.status).to.eql(\"requires_customer_action\");",
" },",
" );",
"}",
- "",
- "// Response body should have \"next_action.type\"",
- "pm.test(",
- " \"[POST]::/payments - Content check if 'next_action.type' exists\",",
- " function () {",
- " pm.expect(typeof jsonData.next_action.type !== \"undefined\").to.be.true;",
- " },",
- ");",
- "",
- "// Response body should have value \"ach\" for \"payment_method_type\"",
- "if (jsonData?.payment_method_type) {",
- " pm.test(",
- " \"[POST]::/payments/:id/confirm - Content check if value for 'payment_method_type' matches 'ach'\",",
- " function () {",
- " pm.expect(jsonData.payment_method_type).to.eql(\"ach\");",
- " },",
- " );",
- "}",
- "",
- "// Response body should have value \"display_bank_transfer_information\" for \"next_action.type\"",
- "if (jsonData?.next_action.type) {",
- " pm.test(",
- " \"[POST]::/payments/:id/confirm - Content check if value for 'payment_method_type' matches 'display_bank_transfer_information'\",",
- " function () {",
- " pm.expect(jsonData.next_action.type).to.eql(",
- " \"display_bank_transfer_information\",",
- " );",
- " },",
- " );",
- "}",
- "",
- "// Response body should have value \"stripe\" for \"connector\"",
- "if (jsonData?.connector) {",
- " pm.test(",
- " \"[POST]::/payments/:id/confirm - Content check if value for 'connector' matches 'stripe'\",",
- " function () {",
- " pm.expect(jsonData.connector).to.eql(\"stripe\");",
- " },",
- " );",
- "}",
- ""
- ],
- "type": "text/javascript"
- }
- },
- {
- "listen": "prerequest",
- "script": {
- "exec": [
""
],
"type": "text/javascript"
@@ -17338,55 +16458,27 @@
}
],
"request": {
- "auth": {
- "type": "apikey",
- "apikey": [
- {
- "key": "value",
- "value": "{{publishable_key}}",
- "type": "string"
- },
- {
- "key": "key",
- "value": "api-key",
- "type": "string"
- },
- {
- "key": "in",
- "value": "header",
- "type": "string"
- }
- ]
- },
- "method": "POST",
+ "method": "GET",
"header": [
- {
- "key": "Content-Type",
- "value": "application/json"
- },
{
"key": "Accept",
"value": "application/json"
}
],
- "body": {
- "mode": "raw",
- "options": {
- "raw": {
- "language": "json"
- }
- },
- "raw": "{\"payment_method\":\"bank_transfer\",\"payment_method_type\":\"ach\",\"payment_method_data\":{\"bank_transfer\":{\"ach_bank_transfer\":{\"billing_details\":{\"email\":\"johndoe@example.com\"}}}},\"client_secret\":\"{{client_secret}}\"}"
- },
"url": {
- "raw": "{{baseUrl}}/payments/:id/confirm",
+ "raw": "{{baseUrl}}/payments/:id?force_sync=true",
"host": [
"{{baseUrl}}"
],
"path": [
"payments",
- ":id",
- "confirm"
+ ":id"
+ ],
+ "query": [
+ {
+ "key": "force_sync",
+ "value": "true"
+ }
],
"variable": [
{
@@ -17396,31 +16488,36 @@
}
]
},
- "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API"
+ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
},
"response": []
- },
+ }
+ ]
+ },
+ {
+ "name": "Scenario21-Wallet-Wechatpay",
+ "item": [
{
- "name": "Payments - Retrieve",
+ "name": "Payments - Create",
"event": [
{
"listen": "test",
"script": {
"exec": [
"// Validate status 2xx",
- "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
" pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
- "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {",
+ "pm.test(\"[POST]::/payments - 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(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
" pm.response.to.have.jsonBody();",
"});",
"",
@@ -17469,12 +16566,12 @@
" );",
"}",
"",
- "// Response body should have value \"requires_customer_action\" for \"status\"",
+ "// Response body should have value \"requires_payment_method\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments:id - Content check if value for 'status' matches 'requires_customer_action'\",",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'\",",
" function () {",
- " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");",
+ " pm.expect(jsonData.status).to.eql(\"requires_payment_method\");",
" },",
" );",
"}",
@@ -17485,66 +16582,63 @@
}
],
"request": {
- "method": "GET",
+ "method": "POST",
"header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
{
"key": "Accept",
"value": "application/json"
}
],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":800,\"currency\":\"USD\",\"confirm\":false,\"business_country\":\"US\",\"business_label\":\"default\",\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":800,\"customer_id\":\"poll\",\"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\",\"statement_descriptor_name\":\"Juspay\",\"statement_descriptor_suffix\":\"Router\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}"
+ },
"url": {
- "raw": "{{baseUrl}}/payments/:id?force_sync=true",
+ "raw": "{{baseUrl}}/payments",
"host": [
"{{baseUrl}}"
],
"path": [
- "payments",
- ":id"
- ],
- "query": [
- {
- "key": "force_sync",
- "value": "true"
- }
- ],
- "variable": [
- {
- "key": "id",
- "value": "{{payment_id}}",
- "description": "(Required) unique payment id"
- }
+ "payments"
]
},
- "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
},
"response": []
- }
- ]
- },
- {
- "name": "Scenario20-Bank Debit-ach",
- "item": [
+ },
{
- "name": "Payments - Create",
+ "name": "Payments - Confirm",
"event": [
{
"listen": "test",
"script": {
"exec": [
"// Validate status 2xx",
- "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ "pm.test(\"[POST]::/payments/:id/confirm - Status code is 2xx\", function () {",
" pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
- "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
- " \"application/json\",",
- " );",
- "});",
+ "pm.test(",
+ " \"[POST]::/payments/:id/confirm - 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]::/payments - Response has JSON Body\", function () {",
+ "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {",
" pm.response.to.have.jsonBody();",
"});",
"",
@@ -17596,28 +16690,86 @@
"// Response body should have value \"requires_customer_action\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments - Content check if value for 'status' matches 'requires_customer_action'\",",
+ " \"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'requires_customer_action'\",",
" function () {",
" pm.expect(jsonData.status).to.eql(\"requires_customer_action\");",
" },",
" );",
"}",
- ""
- ],
- "type": "text/javascript"
- }
- },
- {
- "listen": "prerequest",
- "script": {
- "exec": [
- ""
- ],
+ "",
+ "// Response body should have \"next_action.type\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'next_action.type' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.next_action.type !== \"undefined\").to.be.true;",
+ " },",
+ ");",
+ "",
+ "// Response body should have value \"ach\" for \"payment_method_type\"",
+ "if (jsonData?.payment_method_type) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id/confirm - Content check if value for 'payment_method_type' matches 'we_chat_pay'\",",
+ " function () {",
+ " pm.expect(jsonData.payment_method_type).to.eql(\"we_chat_pay\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"qr_code_information\" for \"next_action.type\"",
+ "if (jsonData?.next_action.type) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id/confirm - Content check if value for 'payment_method_type' matches 'qr_code_information'\",",
+ " function () {",
+ " pm.expect(jsonData.next_action.type).to.eql(\"qr_code_information\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"stripe\" for \"connector\"",
+ "if (jsonData?.connector) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id/confirm - Content check if value for 'connector' matches 'stripe'\",",
+ " function () {",
+ " pm.expect(jsonData.connector).to.eql(\"stripe\");",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ },
+ {
+ "listen": "prerequest",
+ "script": {
+ "exec": [
+ ""
+ ],
"type": "text/javascript"
}
}
],
"request": {
+ "auth": {
+ "type": "apikey",
+ "apikey": [
+ {
+ "key": "value",
+ "value": "{{publishable_key}}",
+ "type": "string"
+ },
+ {
+ "key": "key",
+ "value": "api-key",
+ "type": "string"
+ },
+ {
+ "key": "in",
+ "value": "header",
+ "type": "string"
+ }
+ ]
+ },
"method": "POST",
"header": [
{
@@ -17636,18 +16788,27 @@
"language": "json"
}
},
- "raw": "{\"amount\":1800,\"currency\":\"USD\",\"confirm\":true,\"business_label\":\"default\",\"capture_method\":\"automatic\",\"connector\":[\"stripe\"],\"customer_id\":\"klarna\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"authentication_type\":\"three_ds\",\"email\":\"guest@example.com\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"return_url\":\"https://google.com\",\"statement_descriptor_name\":\"Juspay\",\"statement_descriptor_suffix\":\"Router\",\"setup_future_usage\":\"off_session\",\"business_country\":\"US\",\"mandate_data\":{\"customer_acceptance\":{\"acceptance_type\":\"online\",\"accepted_at\":\"2022-09-10T10:11:12Z\",\"online\":{\"ip_address\":\"123.32.25.123\",\"user_agent\":\"Mozilla/5.0 (Linux; Android 12; SM-S906N Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/80.0.3987.119 Mobile Safari/537.36\"}},\"mandate_type\":{\"single_use\":{\"amount\":6540,\"currency\":\"USD\"}}},\"payment_method\":\"bank_debit\",\"payment_method_type\":\"ach\",\"payment_method_data\":{\"bank_debit\":{\"ach_bank_debit\":{\"billing_details\":{\"name\":\"John Doe\",\"email\":\"johndoe@example.com\"},\"account_number\":\"000123456789\",\"routing_number\":\"110000000\"}}},\"metadata\":{\"order_details\":{\"product_name\":\"Apple iphone 15\",\"quantity\":1,\"amount\":1800,\"account_name\":\"transaction_processing\"}},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}"
+ "raw": "{\"payment_method\":\"wallet\",\"payment_method_type\":\"we_chat_pay\",\"payment_method_data\":{\"wallet\":{\"we_chat_pay_qr\":{}}},\"client_secret\":\"{{client_secret}}\"}"
},
"url": {
- "raw": "{{baseUrl}}/payments",
+ "raw": "{{baseUrl}}/payments/:id/confirm",
"host": [
"{{baseUrl}}"
],
"path": [
- "payments"
+ "payments",
+ ":id",
+ "confirm"
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
]
},
- "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API"
},
"response": []
},
@@ -17773,7 +16934,7 @@
]
},
{
- "name": "Scenario21-Wallet-Wechatpay",
+ "name": "Scenario22- Update address and List Payment method",
"item": [
{
"name": "Payments - Create",
@@ -17782,77 +16943,62 @@
"listen": "test",
"script": {
"exec": [
- "// Validate status 2xx",
+ "// Validate status 2xx ",
"pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
+ " pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
"pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
- " \"application/json\",",
- " );",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");",
"});",
"",
- "// Validate if response has JSON Body",
+ "// Validate if response has JSON Body ",
"pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
- " pm.response.to.have.jsonBody();",
+ " pm.response.to.have.jsonBody();",
"});",
"",
"// Set response object as internal variable",
"let jsonData = {};",
- "try {",
- " jsonData = pm.response.json();",
- "} catch (e) {}",
+ "try {jsonData = pm.response.json();}catch(e){}",
"",
"// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
"if (jsonData?.payment_id) {",
- " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
- " console.log(",
- " \"- use {{payment_id}} as collection variable for value\",",
- " jsonData.payment_id,",
- " );",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);",
"} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
- " );",
- "}",
+ " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');",
+ "};",
+ "",
"",
"// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
"if (jsonData?.mandate_id) {",
- " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
- " console.log(",
- " \"- use {{mandate_id}} as collection variable for value\",",
- " jsonData.mandate_id,",
- " );",
+ " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);",
"} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
- " );",
- "}",
+ " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');",
+ "};",
"",
"// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
"if (jsonData?.client_secret) {",
- " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
- " console.log(",
- " \"- use {{client_secret}} as collection variable for value\",",
- " jsonData.client_secret,",
- " );",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);",
"} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
- " );",
- "}",
+ " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');",
+ "};",
"",
+ "// pm.collectionVariables - Set customer_id as variable for jsonData.customer_id",
+ "if (jsonData?.customer_id) {",
+ " pm.collectionVariables.set(\"customer_id\", jsonData.customer_id);",
+ " console.log(\"- use {{customer_id}} as collection variable for value\",jsonData.customer_id);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{customer_id}}, as jsonData.customer_id is undefined.');",
+ "};",
"// Response body should have value \"requires_payment_method\" for \"status\"",
"if (jsonData?.status) {",
- " pm.test(",
- " \"[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'\",",
- " function () {",
- " pm.expect(jsonData.status).to.eql(\"requires_payment_method\");",
- " },",
- " );",
- "}",
+ "pm.test(\"[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'\", function() {",
+ " pm.expect(jsonData.status).to.eql(\"requires_payment_method\");",
+ "})};",
""
],
"type": "text/javascript"
@@ -17878,7 +17024,7 @@
"language": "json"
}
},
- "raw": "{\"amount\":800,\"currency\":\"USD\",\"confirm\":false,\"business_country\":\"US\",\"business_label\":\"default\",\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":800,\"customer_id\":\"poll\",\"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\",\"statement_descriptor_name\":\"Juspay\",\"statement_descriptor_suffix\":\"Router\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}"
+ "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://duck.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"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",
@@ -17894,134 +17040,63 @@
"response": []
},
{
- "name": "Payments - Confirm",
+ "name": "List Payment Methods for a Merchant",
"event": [
{
"listen": "test",
"script": {
"exec": [
- "// Validate status 2xx",
- "pm.test(\"[POST]::/payments/:id/confirm - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
+ "// Validate status 2xx ",
+ "pm.test(\"[GET]::/payment_methods/:merchant_id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
- "pm.test(",
- " \"[POST]::/payments/:id/confirm - 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]::/payments/:id/confirm - Response has JSON Body\", function () {",
- " pm.response.to.have.jsonBody();",
+ "pm.test(\"[GET]::/payment_methods/:merchant_id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");",
"});",
"",
- "// Set response object as internal variable",
- "let jsonData = {};",
- "try {",
- " jsonData = pm.response.json();",
- "} catch (e) {}",
+ "// Parse the response body as JSON",
+ "var responseBody = pm.response.json();",
"",
- "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
- "if (jsonData?.payment_id) {",
- " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
- " console.log(",
- " \"- use {{payment_id}} as collection variable for value\",",
- " jsonData.payment_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
- " );",
- "}",
+ "// Check if \"payment_methods\" array contains a \"payment_method\" with the value \"card\"",
+ "pm.test(\"[GET]::/payment_methods/:merchant_id -Content Check if payment_method matches 'card'\", function () {",
+ " var paymentMethods = responseBody.payment_methods;",
+ " var cardPaymentMethod = paymentMethods.find(function (method) {",
+ " return method.payment_method == \"card\";",
+ " });",
+ "});",
"",
- "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
- "if (jsonData?.mandate_id) {",
- " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
- " console.log(",
- " \"- use {{mandate_id}} as collection variable for value\",",
- " jsonData.mandate_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
- " );",
- "}",
+ "// Check if \"payment_methods\" array contains a \"payment_method\" with the value \"pay_later\"",
+ "pm.test(\"[GET]::/payment_methods/:merchant_id -Content Check if payment_method matches 'pay_later'\", function () {",
+ " var paymentMethods = responseBody.payment_methods;",
+ " var cardPaymentMethod = paymentMethods.find(function (method) {",
+ " return method.payment_method == \"pay_later\";",
+ " });",
+ "});",
+ "// Check if \"payment_methods\" array contains a \"payment_method\" with the value \"wallet\"",
+ "pm.test(\"[GET]::/payment_methods/:merchant_id -Content Check if payment_method matches 'wallet'\", function () {",
+ " var paymentMethods = responseBody.payment_methods;",
+ " var cardPaymentMethod = paymentMethods.find(function (method) {",
+ " return method.payment_method == \"wallet\";",
+ " });",
+ "});",
"",
- "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
- "if (jsonData?.client_secret) {",
- " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
- " console.log(",
- " \"- use {{client_secret}} as collection variable for value\",",
- " jsonData.client_secret,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
- " );",
- "}",
+ "// Check if \"payment_methods\" array contains a \"payment_method\" with the value \"bank_debit\"",
+ "pm.test(\"[GET]::/payment_methods/:merchant_id -Content Check if payment_method matches 'bank_debit'\", function () {",
+ " var paymentMethods = responseBody.payment_methods;",
+ " var cardPaymentMethod = paymentMethods.find(function (method) {",
+ " return method.payment_method == \"bank_debit\";",
+ " });",
+ "});",
"",
- "// Response body should have value \"requires_customer_action\" for \"status\"",
- "if (jsonData?.status) {",
- " pm.test(",
- " \"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'requires_customer_action'\",",
- " function () {",
- " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");",
- " },",
- " );",
- "}",
- "",
- "// Response body should have \"next_action.type\"",
- "pm.test(",
- " \"[POST]::/payments - Content check if 'next_action.type' exists\",",
- " function () {",
- " pm.expect(typeof jsonData.next_action.type !== \"undefined\").to.be.true;",
- " },",
- ");",
- "",
- "// Response body should have value \"ach\" for \"payment_method_type\"",
- "if (jsonData?.payment_method_type) {",
- " pm.test(",
- " \"[POST]::/payments/:id/confirm - Content check if value for 'payment_method_type' matches 'we_chat_pay'\",",
- " function () {",
- " pm.expect(jsonData.payment_method_type).to.eql(\"we_chat_pay\");",
- " },",
- " );",
- "}",
- "",
- "// Response body should have value \"qr_code_information\" for \"next_action.type\"",
- "if (jsonData?.next_action.type) {",
- " pm.test(",
- " \"[POST]::/payments/:id/confirm - Content check if value for 'payment_method_type' matches 'qr_code_information'\",",
- " function () {",
- " pm.expect(jsonData.next_action.type).to.eql(\"qr_code_information\");",
- " },",
- " );",
- "}",
- "",
- "// Response body should have value \"stripe\" for \"connector\"",
- "if (jsonData?.connector) {",
- " pm.test(",
- " \"[POST]::/payments/:id/confirm - Content check if value for 'connector' matches 'stripe'\",",
- " function () {",
- " pm.expect(jsonData.connector).to.eql(\"stripe\");",
- " },",
- " );",
- "}",
- ""
- ],
- "type": "text/javascript"
- }
- },
- {
- "listen": "prerequest",
- "script": {
- "exec": [
- ""
+ "// Check if \"payment_methods\" array contains a \"payment_method\" with the value \"bank_transfer\"",
+ "pm.test(\"[GET]::/payment_methods/:merchant_id -Content Check if payment_method matches 'bank_transfer'\", function () {",
+ " var paymentMethods = responseBody.payment_methods;",
+ " var cardPaymentMethod = paymentMethods.find(function (method) {",
+ " return method.payment_method == \"bank_transfer\";",
+ " });",
+ "});"
],
"type": "text/javascript"
}
@@ -18048,126 +17123,78 @@
}
]
},
- "method": "POST",
+ "method": "GET",
"header": [
- {
- "key": "Content-Type",
- "value": "application/json"
- },
{
"key": "Accept",
"value": "application/json"
}
],
- "body": {
- "mode": "raw",
- "options": {
- "raw": {
- "language": "json"
- }
- },
- "raw": "{\"payment_method\":\"wallet\",\"payment_method_type\":\"we_chat_pay\",\"payment_method_data\":{\"wallet\":{\"we_chat_pay_qr\":{}}},\"client_secret\":\"{{client_secret}}\"}"
- },
"url": {
- "raw": "{{baseUrl}}/payments/:id/confirm",
+ "raw": "{{baseUrl}}/account/payment_methods?client_secret={{client_secret}}",
"host": [
"{{baseUrl}}"
],
"path": [
- "payments",
- ":id",
- "confirm"
+ "account",
+ "payment_methods"
],
- "variable": [
+ "query": [
{
- "key": "id",
- "value": "{{payment_id}}",
- "description": "(Required) unique payment id"
+ "key": "client_secret",
+ "value": "{{client_secret}}"
}
]
},
- "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API"
+ "description": "To filter and list the applicable payment methods for a particular merchant id."
},
"response": []
},
{
- "name": "Payments - Retrieve",
+ "name": "Payments - Update",
"event": [
{
"listen": "test",
"script": {
"exec": [
- "// Validate status 2xx",
- "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
+ "// Validate status 2xx ",
+ "pm.test(\"[POST]::/payments/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
- "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
- " \"application/json\",",
- " );",
+ "pm.test(\"[POST]::/payments/:id - 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(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
- " pm.response.to.have.jsonBody();",
+ "// Validate if response has JSON Body ",
+ "pm.test(\"[POST]::/payments/:id - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
"});",
"",
- "// Set response object as internal variable",
- "let jsonData = {};",
- "try {",
- " jsonData = pm.response.json();",
- "} catch (e) {}",
"",
- "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
- "if (jsonData?.payment_id) {",
- " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
- " console.log(",
- " \"- use {{payment_id}} as collection variable for value\",",
- " jsonData.payment_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
- " );",
- "}",
+ "// Parse the JSON response",
+ "var jsonData = pm.response.json();",
"",
- "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
- "if (jsonData?.mandate_id) {",
- " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
- " console.log(",
- " \"- use {{mandate_id}} as collection variable for value\",",
- " jsonData.mandate_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
- " );",
- "}",
+ "// Check if the 'currency' is equal to \"EUR\"",
+ "pm.test(\"[POST]::/payments/:id -Content Check if 'currency' matches 'EUR' \", function () {",
+ " pm.expect(jsonData.currency).to.eql(\"EUR\");",
+ "});",
"",
- "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
- "if (jsonData?.client_secret) {",
- " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
- " console.log(",
- " \"- use {{client_secret}} as collection variable for value\",",
- " jsonData.client_secret,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
- " );",
- "}",
+ "// Extract the \"country\" field from the JSON data",
+ "var country = jsonData.billing.address.country;",
"",
- "// Response body should have value \"requires_customer_action\" for \"status\"",
- "if (jsonData?.status) {",
- " pm.test(",
- " \"[POST]::/payments:id - Content check if value for 'status' matches 'requires_customer_action'\",",
- " function () {",
- " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");",
- " },",
- " );",
- "}",
+ "// Check if the country is \"NL\"",
+ "pm.test(\"[POST]::/payments/:id -Content Check if billing 'Country' matches NL (Netherlands)\", function () {",
+ " pm.expect(country).to.equal(\"NL\");",
+ "});",
+ "",
+ "var country1 = jsonData.shipping.address.country;",
+ "",
+ "// Check if the country is \"NL\"",
+ "pm.test(\"[POST]::/payments/:id -Content Check if shipping 'Country' matches NL (Netherlands)\", function () {",
+ " pm.expect(country1).to.equal(\"NL\");",
+ "});",
""
],
"type": "text/javascript"
@@ -18175,15 +17202,28 @@
}
],
"request": {
- "method": "GET",
+ "method": "POST",
"header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
{
"key": "Accept",
"value": "application/json"
}
],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"currency\":\"EUR\",\"shipping\":{\"address\":{\"line1\":\"1468\",\"line2\":\"Koramangala \",\"line3\":\"Koramangala \",\"city\":\"Bangalore\",\"state\":\"Karnataka\",\"zip\":\"560065\",\"country\":\"NL\",\"first_name\":\"Preeetam\",\"last_name\":\"Rev\"},\"phone\":{\"number\":\"8796455689\",\"country_code\":\"+91\"}},\"billing\":{\"address\":{\"line1\":\"1468\",\"line2\":\"Koramangala \",\"line3\":\"Koramangala \",\"city\":\"Bangalore\",\"state\":\"Karnataka\",\"zip\":\"560065\",\"country\":\"NL\",\"first_name\":\"Preeetam\",\"last_name\":\"Rev\"},\"phone\":{\"number\":\"8796455689\",\"country_code\":\"+91\"}}}"
+ },
"url": {
- "raw": "{{baseUrl}}/payments/:id?force_sync=true",
+ "raw": "{{baseUrl}}/payments/:id",
"host": [
"{{baseUrl}}"
],
@@ -18191,188 +17231,59 @@
"payments",
":id"
],
- "query": [
- {
- "key": "force_sync",
- "value": "true"
- }
- ],
"variable": [
{
"key": "id",
- "value": "{{payment_id}}",
- "description": "(Required) unique payment id"
+ "value": "{{payment_id}}"
}
]
},
- "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ "description": "To update the properties of a PaymentIntent object. This may include attaching a payment method, or attaching customer object or metadata fields after the Payment is created "
},
"response": []
- }
- ]
- },
- {
- "name": "Scenario22- Update address and List Payment method",
- "item": [
+ },
{
- "name": "Payments - Create",
+ "name": "List Payment Methods for a Merchant-copy",
"event": [
{
"listen": "test",
"script": {
"exec": [
"// Validate status 2xx ",
- "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ "pm.test(\"[GET]::/payment_methods/:merchant_id - Status code is 2xx\", function () {",
" pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
- "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ "pm.test(\"[GET]::/payment_methods/:merchant_id - 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]::/payments - Response has JSON Body\", function () {",
- " pm.response.to.have.jsonBody();",
- "});",
"",
- "// Set response object as internal variable",
- "let jsonData = {};",
- "try {jsonData = pm.response.json();}catch(e){}",
+ "// Parse the response body as JSON",
+ "var responseBody = pm.response.json();",
"",
- "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
- "if (jsonData?.payment_id) {",
- " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
- " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);",
- "} else {",
- " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');",
- "};",
+ "// Check if \"payment_methods\" array contains a \"payment_method\" with the value \"card\"",
+ "pm.test(\"[GET]::/payment_methods/:merchant_id -Content Check if payment_method matches 'card'\", function () {",
+ " var paymentMethods = responseBody.payment_methods;",
+ " var cardPaymentMethod = paymentMethods.find(function (method) {",
+ " return method.payment_method == \"card\";",
+ " });",
+ "});",
"",
+ "// Check if \"payment_methods\" array contains a \"payment_method\" with the value \"ideal\"",
+ "pm.test(\"[GET]::/payment_methods/:merchant_id - Content Check if payment_method matches 'ideal'\", function () {",
+ " var paymentMethods = responseBody.payment_methods;",
+ " var cardPaymentMethod = paymentMethods.find(function (method) {",
+ " return method.payment_method == \"ideal\";",
+ " });",
+ "});",
"",
- "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
- "if (jsonData?.mandate_id) {",
- " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
- " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);",
- "} else {",
- " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');",
- "};",
- "",
- "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
- "if (jsonData?.client_secret) {",
- " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
- " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);",
- "} else {",
- " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');",
- "};",
- "",
- "// pm.collectionVariables - Set customer_id as variable for jsonData.customer_id",
- "if (jsonData?.customer_id) {",
- " pm.collectionVariables.set(\"customer_id\", jsonData.customer_id);",
- " console.log(\"- use {{customer_id}} as collection variable for value\",jsonData.customer_id);",
- "} else {",
- " console.log('INFO - Unable to assign variable {{customer_id}}, as jsonData.customer_id is undefined.');",
- "};",
- "// Response body should have value \"requires_payment_method\" for \"status\"",
- "if (jsonData?.status) {",
- "pm.test(\"[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'\", function() {",
- " pm.expect(jsonData.status).to.eql(\"requires_payment_method\");",
- "})};",
- ""
- ],
- "type": "text/javascript"
- }
- }
- ],
- "request": {
- "method": "POST",
- "header": [
- {
- "key": "Content-Type",
- "value": "application/json"
- },
- {
- "key": "Accept",
- "value": "application/json"
- }
- ],
- "body": {
- "mode": "raw",
- "options": {
- "raw": {
- "language": "json"
- }
- },
- "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://duck.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"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",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments"
- ]
- },
- "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
- },
- "response": []
- },
- {
- "name": "List Payment Methods for a Merchant",
- "event": [
- {
- "listen": "test",
- "script": {
- "exec": [
- "// Validate status 2xx ",
- "pm.test(\"[GET]::/payment_methods/:merchant_id - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
- "});",
- "",
- "// Validate if response header has matching content-type",
- "pm.test(\"[GET]::/payment_methods/:merchant_id - Content-Type is application/json\", function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");",
- "});",
- "",
- "// Parse the response body as JSON",
- "var responseBody = pm.response.json();",
- "",
- "// Check if \"payment_methods\" array contains a \"payment_method\" with the value \"card\"",
- "pm.test(\"[GET]::/payment_methods/:merchant_id -Content Check if payment_method matches 'card'\", function () {",
- " var paymentMethods = responseBody.payment_methods;",
- " var cardPaymentMethod = paymentMethods.find(function (method) {",
- " return method.payment_method == \"card\";",
- " });",
- "});",
- "",
- "// Check if \"payment_methods\" array contains a \"payment_method\" with the value \"pay_later\"",
- "pm.test(\"[GET]::/payment_methods/:merchant_id -Content Check if payment_method matches 'pay_later'\", function () {",
- " var paymentMethods = responseBody.payment_methods;",
- " var cardPaymentMethod = paymentMethods.find(function (method) {",
- " return method.payment_method == \"pay_later\";",
- " });",
- "});",
- "// Check if \"payment_methods\" array contains a \"payment_method\" with the value \"wallet\"",
- "pm.test(\"[GET]::/payment_methods/:merchant_id -Content Check if payment_method matches 'wallet'\", function () {",
- " var paymentMethods = responseBody.payment_methods;",
- " var cardPaymentMethod = paymentMethods.find(function (method) {",
- " return method.payment_method == \"wallet\";",
- " });",
- "});",
- "",
- "// Check if \"payment_methods\" array contains a \"payment_method\" with the value \"bank_debit\"",
- "pm.test(\"[GET]::/payment_methods/:merchant_id -Content Check if payment_method matches 'bank_debit'\", function () {",
- " var paymentMethods = responseBody.payment_methods;",
- " var cardPaymentMethod = paymentMethods.find(function (method) {",
- " return method.payment_method == \"bank_debit\";",
- " });",
- "});",
- "",
- "// Check if \"payment_methods\" array contains a \"payment_method\" with the value \"bank_transfer\"",
- "pm.test(\"[GET]::/payment_methods/:merchant_id -Content Check if payment_method matches 'bank_transfer'\", function () {",
+ "// Check if \"payment_methods\" array contains a \"payment_method\" with the value \"bank_redirect\"",
+ "pm.test(\"[GET]::/payment_methods/:merchant_id -Content Check if payment_method matches 'bank_redirect'\", function () {",
" var paymentMethods = responseBody.payment_methods;",
" var cardPaymentMethod = paymentMethods.find(function (method) {",
- " return method.payment_method == \"bank_transfer\";",
+ " return method.payment_method == \"bank_redirect\";",
" });",
"});"
],
@@ -18406,12 +17317,6 @@
{
"key": "Accept",
"value": "application/json"
- },
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
}
],
"url": {
@@ -18435,50 +17340,37 @@
"response": []
},
{
- "name": "Payments - Update",
+ "name": "Payments - Confirm",
"event": [
{
"listen": "test",
"script": {
"exec": [
"// Validate status 2xx ",
- "pm.test(\"[POST]::/payments/:id - Status code is 2xx\", function () {",
+ "pm.test(\"[POST]::/payments/:id/confirm - Status code is 2xx\", function () {",
" pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
- "pm.test(\"[POST]::/payments/:id - Content-Type is application/json\", function () {",
+ "pm.test(\"[POST]::/payments/:id/confirm - Content-Type is application/json\", function () {",
" pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");",
"});",
"",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {jsonData = pm.response.json();}catch(e){}",
+ "",
"// Validate if response has JSON Body ",
- "pm.test(\"[POST]::/payments/:id - Response has JSON Body\", function () {",
+ "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {",
" pm.response.to.have.jsonBody();",
"});",
"",
+ "//// Response body should have value \"requires_customer_action\" for \"status\"",
+ "if (jsonData?.status) {",
+ "pm.test(\"[POST]::/payments - Content check if value for 'status' matches 'requires_customer_action'\", function() {",
+ " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");",
+ "})};",
"",
- "// Parse the JSON response",
- "var jsonData = pm.response.json();",
- "",
- "// Check if the 'currency' is equal to \"EUR\"",
- "pm.test(\"[POST]::/payments/:id -Content Check if 'currency' matches 'EUR' \", function () {",
- " pm.expect(jsonData.currency).to.eql(\"EUR\");",
- "});",
- "",
- "// Extract the \"country\" field from the JSON data",
- "var country = jsonData.billing.address.country;",
- "",
- "// Check if the country is \"NL\"",
- "pm.test(\"[POST]::/payments/:id -Content Check if billing 'Country' matches NL (Netherlands)\", function () {",
- " pm.expect(country).to.equal(\"NL\");",
- "});",
- "",
- "var country1 = jsonData.shipping.address.country;",
- "",
- "// Check if the country is \"NL\"",
- "pm.test(\"[POST]::/payments/:id -Content Check if shipping 'Country' matches NL (Netherlands)\", function () {",
- " pm.expect(country1).to.equal(\"NL\");",
- "});",
""
],
"type": "text/javascript"
@@ -18486,6 +17378,26 @@
}
],
"request": {
+ "auth": {
+ "type": "apikey",
+ "apikey": [
+ {
+ "key": "value",
+ "value": "{{publishable_key}}",
+ "type": "string"
+ },
+ {
+ "key": "key",
+ "value": "api-key",
+ "type": "string"
+ },
+ {
+ "key": "in",
+ "value": "header",
+ "type": "string"
+ }
+ ]
+ },
"method": "POST",
"header": [
{
@@ -18504,16 +17416,17 @@
"language": "json"
}
},
- "raw": "{\"currency\":\"EUR\",\"shipping\":{\"address\":{\"line1\":\"1468\",\"line2\":\"Koramangala \",\"line3\":\"Koramangala \",\"city\":\"Bangalore\",\"state\":\"Karnataka\",\"zip\":\"560065\",\"country\":\"NL\",\"first_name\":\"Preeetam\",\"last_name\":\"Rev\"},\"phone\":{\"number\":\"8796455689\",\"country_code\":\"+91\"}},\"billing\":{\"address\":{\"line1\":\"1468\",\"line2\":\"Koramangala \",\"line3\":\"Koramangala \",\"city\":\"Bangalore\",\"state\":\"Karnataka\",\"zip\":\"560065\",\"country\":\"NL\",\"first_name\":\"Preeetam\",\"last_name\":\"Rev\"},\"phone\":{\"number\":\"8796455689\",\"country_code\":\"+91\"}}}"
+ "raw": "{\"client_secret\":\"{{client_secret}}\",\"payment_method\":\"bank_redirect\",\"payment_method_type\":\"ideal\",\"payment_method_data\":{\"bank_redirect\":{\"ideal\":{\"billing_details\":{\"billing_name\":\"Example\",\"email\":\"guest@example.com\"},\"bank_name\":\"ing\"}}},\"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\":7000,\"currency\":\"USD\",\"start_date\":\"2023-04-21T00:00:00Z\",\"end_date\":\"2023-05-21T00:00:00Z\",\"metadata\":{\"frequency\":\"13\"}}}},\"setup_future_usage\":\"off_session\",\"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\":\"128.0.0.1\"}}"
},
"url": {
- "raw": "{{baseUrl}}/payments/:id",
+ "raw": "{{baseUrl}}/payments/:id/confirm",
"host": [
"{{baseUrl}}"
],
"path": [
"payments",
- ":id"
+ ":id",
+ "confirm"
],
"variable": [
{
@@ -18522,246 +17435,43 @@
}
]
},
- "description": "To update the properties of a PaymentIntent object. This may include attaching a payment method, or attaching customer object or metadata fields after the Payment is created "
+ "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API"
},
"response": []
},
{
- "name": "List Payment Methods for a Merchant-copy",
+ "name": "Payments - Retrieve",
"event": [
{
"listen": "test",
"script": {
"exec": [
"// Validate status 2xx ",
- "pm.test(\"[GET]::/payment_methods/:merchant_id - Status code is 2xx\", function () {",
+ "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
" pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
- "pm.test(\"[GET]::/payment_methods/:merchant_id - Content-Type is application/json\", function () {",
+ "pm.test(\"[GET]::/payments/:id - 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(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
"",
- "// Parse the response body as JSON",
- "var responseBody = pm.response.json();",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {jsonData = pm.response.json();}catch(e){}",
"",
- "// Check if \"payment_methods\" array contains a \"payment_method\" with the value \"card\"",
- "pm.test(\"[GET]::/payment_methods/:merchant_id -Content Check if payment_method matches 'card'\", function () {",
- " var paymentMethods = responseBody.payment_methods;",
- " var cardPaymentMethod = paymentMethods.find(function (method) {",
- " return method.payment_method == \"card\";",
- " });",
- "});",
- "",
- "// Check if \"payment_methods\" array contains a \"payment_method\" with the value \"ideal\"",
- "pm.test(\"[GET]::/payment_methods/:merchant_id - Content Check if payment_method matches 'ideal'\", function () {",
- " var paymentMethods = responseBody.payment_methods;",
- " var cardPaymentMethod = paymentMethods.find(function (method) {",
- " return method.payment_method == \"ideal\";",
- " });",
- "});",
- "",
- "// Check if \"payment_methods\" array contains a \"payment_method\" with the value \"bank_redirect\"",
- "pm.test(\"[GET]::/payment_methods/:merchant_id -Content Check if payment_method matches 'bank_redirect'\", function () {",
- " var paymentMethods = responseBody.payment_methods;",
- " var cardPaymentMethod = paymentMethods.find(function (method) {",
- " return method.payment_method == \"bank_redirect\";",
- " });",
- "});"
- ],
- "type": "text/javascript"
- }
- }
- ],
- "request": {
- "auth": {
- "type": "apikey",
- "apikey": [
- {
- "key": "value",
- "value": "{{publishable_key}}",
- "type": "string"
- },
- {
- "key": "key",
- "value": "api-key",
- "type": "string"
- },
- {
- "key": "in",
- "value": "header",
- "type": "string"
- }
- ]
- },
- "method": "GET",
- "header": [
- {
- "key": "Accept",
- "value": "application/json"
- },
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- }
- ],
- "url": {
- "raw": "{{baseUrl}}/account/payment_methods?client_secret={{client_secret}}",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "account",
- "payment_methods"
- ],
- "query": [
- {
- "key": "client_secret",
- "value": "{{client_secret}}"
- }
- ]
- },
- "description": "To filter and list the applicable payment methods for a particular merchant id."
- },
- "response": []
- },
- {
- "name": "Payments - Confirm",
- "event": [
- {
- "listen": "test",
- "script": {
- "exec": [
- "// Validate status 2xx ",
- "pm.test(\"[POST]::/payments/:id/confirm - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
- "});",
- "",
- "// Validate if response header has matching content-type",
- "pm.test(\"[POST]::/payments/:id/confirm - Content-Type is application/json\", function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");",
- "});",
- "",
- "// Set response object as internal variable",
- "let jsonData = {};",
- "try {jsonData = pm.response.json();}catch(e){}",
- "",
- "// Validate if response has JSON Body ",
- "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {",
- " pm.response.to.have.jsonBody();",
- "});",
- "",
- "//// Response body should have value \"requires_customer_action\" for \"status\"",
- "if (jsonData?.status) {",
- "pm.test(\"[POST]::/payments - Content check if value for 'status' matches 'requires_customer_action'\", function() {",
- " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");",
- "})};",
- "",
- ""
- ],
- "type": "text/javascript"
- }
- }
- ],
- "request": {
- "auth": {
- "type": "apikey",
- "apikey": [
- {
- "key": "value",
- "value": "{{publishable_key}}",
- "type": "string"
- },
- {
- "key": "key",
- "value": "api-key",
- "type": "string"
- },
- {
- "key": "in",
- "value": "header",
- "type": "string"
- }
- ]
- },
- "method": "POST",
- "header": [
- {
- "key": "Content-Type",
- "value": "application/json"
- },
- {
- "key": "Accept",
- "value": "application/json"
- }
- ],
- "body": {
- "mode": "raw",
- "options": {
- "raw": {
- "language": "json"
- }
- },
- "raw": "{\"client_secret\":\"{{client_secret}}\",\"payment_method\":\"bank_redirect\",\"payment_method_type\":\"ideal\",\"payment_method_data\":{\"bank_redirect\":{\"ideal\":{\"billing_details\":{\"billing_name\":\"Example\",\"email\":\"guest@example.com\"},\"bank_name\":\"ing\"}}},\"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\":7000,\"currency\":\"USD\",\"start_date\":\"2023-04-21T00:00:00Z\",\"end_date\":\"2023-05-21T00:00:00Z\",\"metadata\":{\"frequency\":\"13\"}}}},\"setup_future_usage\":\"off_session\",\"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\":\"128.0.0.1\"}}"
- },
- "url": {
- "raw": "{{baseUrl}}/payments/:id/confirm",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments",
- ":id",
- "confirm"
- ],
- "variable": [
- {
- "key": "id",
- "value": "{{payment_id}}"
- }
- ]
- },
- "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API"
- },
- "response": []
- },
- {
- "name": "Payments - Retrieve",
- "event": [
- {
- "listen": "test",
- "script": {
- "exec": [
- "// Validate status 2xx ",
- "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
- "});",
- "",
- "// Validate if response header has matching content-type",
- "pm.test(\"[GET]::/payments/:id - 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(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
- " pm.response.to.have.jsonBody();",
- "});",
- "",
- "// Set response object as internal variable",
- "let jsonData = {};",
- "try {jsonData = pm.response.json();}catch(e){}",
- "",
- "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
- "if (jsonData?.payment_id) {",
- " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
- " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);",
- "} else {",
- " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');",
- "};",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');",
+ "};",
"",
"",
"// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
@@ -19092,12 +17802,6 @@
"key": "Accept",
"value": "application/json"
},
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- },
{
"key": "publishable_key",
"value": "",
@@ -20193,102 +18897,1398 @@
"",
"// Set response object as internal variable",
"let jsonData = {};",
- "try {jsonData = pm.response.json();}catch(e){}",
- "",
- "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
- "if (jsonData?.payment_id) {",
- " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
- " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);",
- "} else {",
- " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');",
- "};",
- "",
+ "try {jsonData = pm.response.json();}catch(e){}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');",
+ "};",
+ "",
+ "",
+ "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
+ "if (jsonData?.mandate_id) {",
+ " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');",
+ "};",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');",
+ "};",
+ "",
+ "if (jsonData?.customer_id) {",
+ " pm.collectionVariables.set(\"customer_id\", jsonData.customer_id);",
+ " console.log(\"- use {{customer_id}} as collection variable for value\",jsonData.customer_id);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{customer_id}}, as jsonData.customer_id is undefined.');",
+ "};"
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"{{customer_id}}\",\"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\",\"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\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ },
+ {
+ "name": "Save card payments - Confirm",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments/:id/confirm - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(",
+ " \"[POST]::/payments/:id/confirm - 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]::/payments/:id/confirm - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
+ "if (jsonData?.mandate_id) {",
+ " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ " console.log(",
+ " \"- use {{mandate_id}} as collection variable for value\",",
+ " jsonData.mandate_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"adyen\" for \"connector\"",
+ "if (jsonData?.connector) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id/confirm - Content check if value for 'connector' matches 'stripe'\",",
+ " function () {",
+ " pm.expect(jsonData.connector).to.eql(\"stripe\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'succeeded'\", function() {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " })};"
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "auth": {
+ "type": "apikey",
+ "apikey": [
+ {
+ "key": "value",
+ "value": "{{publishable_key}}",
+ "type": "string"
+ },
+ {
+ "key": "key",
+ "value": "api-key",
+ "type": "string"
+ },
+ {
+ "key": "in",
+ "value": "header",
+ "type": "string"
+ }
+ ]
+ },
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"client_secret\":\"{{client_secret}}\",\"payment_method\":\"card\",\"payment_token\":\"{{payment_token}}\"}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id/confirm",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id",
+ "confirm"
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API"
+ },
+ "response": []
+ }
+ ]
+ },
+ {
+ "name": "Scenario26-Save card payment with manual capture",
+ "item": [
+ {
+ "name": "Payments - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx ",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - 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]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {jsonData = pm.response.json();}catch(e){}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');",
+ "};",
+ "",
+ "",
+ "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
+ "if (jsonData?.mandate_id) {",
+ " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');",
+ "};",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');",
+ "};",
+ "",
+ "if (jsonData?.customer_id) {",
+ " pm.collectionVariables.set(\"customer_id\", jsonData.customer_id);",
+ " console.log(\"- use {{customer_id}} as collection variable for value\",jsonData.customer_id);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{customer_id}}, as jsonData.customer_id is undefined.');",
+ "};",
+ "",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}"
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"adyensavecard_{{random_number}}\",\"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\",\"setup_future_usage\":\"on_session\",\"payment_method\":\"card\",\"payment_method_type\":\"credit\",\"payment_method_data\":{\"card\":{\"card_number\":\"371449635398431\",\"card_exp_month\":\"03\",\"card_exp_year\":\"2030\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"7373\"}},\"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\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Retrieve",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/payments/:id - 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(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
+ "if (jsonData?.mandate_id) {",
+ " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ " console.log(",
+ " \"- use {{mandate_id}} as collection variable for value\",",
+ " jsonData.mandate_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"Succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Validate the connector",
+ "pm.test(\"[POST]::/payments - connector\", function () {",
+ " pm.expect(jsonData.connector).to.eql(\"stripe\");",
+ "});",
+ "",
+ "// Response body should have value \"6540\" for \"amount\"",
+ "if (jsonData?.amount) {",
+ " pm.test(",
+ " \"[post]:://payments/:id/capture - Content check if value for 'amount' matches '6540'\",",
+ " function () {",
+ " pm.expect(jsonData.amount).to.eql(6540);",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"6000\" for \"amount_received\"",
+ "if (jsonData?.amount_received) {",
+ " pm.test(",
+ " \"[POST]::/payments:id/capture - Content check if value for 'amount_received' matches '6000'\",",
+ " function () {",
+ " pm.expect(jsonData.amount_received).to.eql(6540);",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"6540\" for \"amount_capturable\"",
+ "if (jsonData?.amount) {",
+ " pm.test(",
+ " \"[post]:://payments/:id/capture - Content check if value for 'amount_capturable' matches 'amount - 540'\",",
+ " function () {",
+ " pm.expect(jsonData.amount_capturable).to.eql(0);",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id?force_sync=true",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id"
+ ],
+ "query": [
+ {
+ "key": "force_sync",
+ "value": "true"
+ }
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ },
+ "response": []
+ },
+ {
+ "name": "List payment methods for a Customer",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx ",
+ "pm.test(\"[GET]::/payment_methods/:customer_id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/payment_methods/:customer_id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {jsonData = pm.response.json();}catch(e){}",
+ "",
+ "if (jsonData?.customer_payment_methods[0]?.payment_token) {",
+ " pm.collectionVariables.set(\"payment_token\", jsonData.customer_payment_methods[0].payment_token);",
+ " console.log(\"- use {{payment_token}} as collection variable for value\", jsonData.customer_payment_methods[0].payment_token);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{payment_token}}, as jsonData.customer_payment_methods[0].payment_token is undefined.');",
+ "}"
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/customers/:customer_id/payment_methods",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "customers",
+ ":customer_id",
+ "payment_methods"
+ ],
+ "query": [
+ {
+ "key": "accepted_country",
+ "value": "co",
+ "disabled": true
+ },
+ {
+ "key": "accepted_country",
+ "value": "pa",
+ "disabled": true
+ },
+ {
+ "key": "accepted_currency",
+ "value": "voluptate ea",
+ "disabled": true
+ },
+ {
+ "key": "accepted_currency",
+ "value": "exercitation",
+ "disabled": true
+ },
+ {
+ "key": "minimum_amount",
+ "value": "100",
+ "disabled": true
+ },
+ {
+ "key": "maximum_amount",
+ "value": "10000000",
+ "disabled": true
+ },
+ {
+ "key": "recurring_payment_enabled",
+ "value": "true",
+ "disabled": true
+ },
+ {
+ "key": "installment_payment_enabled",
+ "value": "true",
+ "disabled": true
+ }
+ ],
+ "variable": [
+ {
+ "key": "customer_id",
+ "value": "{{customer_id}}",
+ "description": "//Pass the customer id"
+ }
+ ]
+ },
+ "description": "To filter and list the applicable payment methods for a particular Customer ID"
+ },
+ "response": []
+ },
+ {
+ "name": "Save card payments - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx ",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - 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]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {jsonData = pm.response.json();}catch(e){}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');",
+ "};",
+ "",
+ "",
+ "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
+ "if (jsonData?.mandate_id) {",
+ " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');",
+ "};",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');",
+ "};",
+ "",
+ "if (jsonData?.customer_id) {",
+ " pm.collectionVariables.set(\"customer_id\", jsonData.customer_id);",
+ " console.log(\"- use {{customer_id}} as collection variable for value\",jsonData.customer_id);",
+ "} else {",
+ " console.log('INFO - Unable to assign variable {{customer_id}}, as jsonData.customer_id is undefined.');",
+ "};"
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"manual\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"{{customer_id}}\",\"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\",\"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\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ },
+ {
+ "name": "Save card payments - Confirm",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments/:id/confirm - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(",
+ " \"[POST]::/payments/:id/confirm - 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]::/payments/:id/confirm - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
+ "if (jsonData?.mandate_id) {",
+ " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ " console.log(",
+ " \"- use {{mandate_id}} as collection variable for value\",",
+ " jsonData.mandate_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"requires_capture\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'requires_capture'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"requires_capture\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "",
+ "// Response body should have value \"stripe\" for \"connector\"",
+ "if (jsonData?.connector) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id/confirm - Content check if value for 'connector' matches 'stripe'\",",
+ " function () {",
+ " pm.expect(jsonData.connector).to.eql(\"stripe\");",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "auth": {
+ "type": "apikey",
+ "apikey": [
+ {
+ "key": "value",
+ "value": "{{publishable_key}}",
+ "type": "string"
+ },
+ {
+ "key": "key",
+ "value": "api-key",
+ "type": "string"
+ },
+ {
+ "key": "in",
+ "value": "header",
+ "type": "string"
+ }
+ ]
+ },
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"client_secret\":\"{{client_secret}}\",\"payment_method\":\"card\",\"payment_token\":\"{{payment_token}}\",\"card_cvc\":\"7373\"}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id/confirm",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id",
+ "confirm"
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Capture",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments/:id/capture - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(",
+ " \"[POST]::/payments/:id/capture - 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]::/payments/:id/capture - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
+ "if (jsonData?.mandate_id) {",
+ " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ " console.log(",
+ " \"- use {{mandate_id}} as collection variable for value\",",
+ " jsonData.mandate_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]:://payments/:id/capture - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Validate the connector",
+ "pm.test(\"[POST]::/payments - connector\", function () {",
+ " pm.expect(jsonData.connector).to.eql(\"stripe\");",
+ "});",
+ "",
+ "// Response body should have value \"6540\" for \"amount\"",
+ "if (jsonData?.amount) {",
+ " pm.test(",
+ " \"[post]:://payments/:id/capture - Content check if value for 'amount' matches '6540'\",",
+ " function () {",
+ " pm.expect(jsonData.amount).to.eql(6540);",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"6000\" for \"amount_received\"",
+ "if (jsonData?.amount_received) {",
+ " pm.test(",
+ " \"[POST]::/payments:id/capture - Content check if value for 'amount_received' matches '6540'\",",
+ " function () {",
+ " pm.expect(jsonData.amount_received).to.eql(6540);",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"6540\" for \"amount_capturable\"",
+ "if (jsonData?.amount_capturable) {",
+ " pm.test(",
+ " \"[post]:://payments/:id/capture - Content check if value for 'amount_capturable' matches 'amount - 540'\",",
+ " function () {",
+ " pm.expect(jsonData.amount_capturable).to.eql(6540);",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount_to_capture\":6540,\"statement_descriptor_name\":\"Joseph\",\"statement_descriptor_suffix\":\"JS\"}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id/capture",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id",
+ "capture"
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "To capture the funds for an uncaptured payment"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Retrieve-copy",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/payments/:id - 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(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
+ "if (jsonData?.mandate_id) {",
+ " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ " console.log(",
+ " \"- use {{mandate_id}} as collection variable for value\",",
+ " jsonData.mandate_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"Succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Validate the connector",
+ "pm.test(\"[POST]::/payments - connector\", function () {",
+ " pm.expect(jsonData.connector).to.eql(\"stripe\");",
+ "});",
+ "",
+ "// Response body should have value \"6540\" for \"amount\"",
+ "if (jsonData?.amount) {",
+ " pm.test(",
+ " \"[post]:://payments/:id/capture - Content check if value for 'amount' matches '6540'\",",
+ " function () {",
+ " pm.expect(jsonData.amount).to.eql(6540);",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"6000\" for \"amount_received\"",
+ "if (jsonData?.amount_received) {",
+ " pm.test(",
+ " \"[POST]::/payments:id/capture - Content check if value for 'amount_received' matches '6540'\",",
+ " function () {",
+ " pm.expect(jsonData.amount_received).to.eql(6540);",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"6540\" for \"amount_capturable\"",
+ "if (jsonData?.amount) {",
+ " pm.test(",
+ " \"[post]:://payments/:id/capture - Content check if value for 'amount_capturable' matches 'amount - 540'\",",
+ " function () {",
+ " pm.expect(jsonData.amount_capturable).to.eql(0);",
+ " },",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id?force_sync=true",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id"
+ ],
+ "query": [
+ {
+ "key": "force_sync",
+ "value": "true"
+ }
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ },
+ "response": []
+ },
+ {
+ "name": "Refunds - Create Copy",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/refunds - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/refunds - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id",
+ "if (jsonData?.refund_id) {",
+ " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);",
+ " console.log(",
+ " \"- use {{refund_id}} as collection variable for value\",",
+ " jsonData.refund_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/refunds - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"540\" for \"amount\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/refunds - Content check if value for 'amount' matches '540'\",",
+ " function () {",
+ " pm.expect(jsonData.amount).to.eql(540);",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Validate the connector",
+ "pm.test(\"[POST]::/payments - connector\", function () {",
+ " pm.expect(jsonData.connector).to.eql(\"stripe\");",
+ "});",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"payment_id\":\"{{payment_id}}\",\"amount\":540,\"reason\":\"Customer returned product\",\"refund_type\":\"instant\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/refunds",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "refunds"
+ ]
+ },
+ "description": "To create a refund against an already processed payment"
+ },
+ "response": []
+ },
+ {
+ "name": "Refunds - Retrieve Copy",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[GET]::/refunds/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/refunds/:id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
"",
- "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
- "if (jsonData?.mandate_id) {",
- " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
- " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);",
+ "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id",
+ "if (jsonData?.refund_id) {",
+ " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);",
+ " console.log(",
+ " \"- use {{refund_id}} as collection variable for value\",",
+ " jsonData.refund_id,",
+ " );",
"} else {",
- " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');",
- "};",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",",
+ " );",
+ "}",
"",
- "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
- "if (jsonData?.client_secret) {",
- " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
- " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);",
- "} else {",
- " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');",
- "};",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/refunds - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
"",
- "if (jsonData?.customer_id) {",
- " pm.collectionVariables.set(\"customer_id\", jsonData.customer_id);",
- " console.log(\"- use {{customer_id}} as collection variable for value\",jsonData.customer_id);",
- "} else {",
- " console.log('INFO - Unable to assign variable {{customer_id}}, as jsonData.customer_id is undefined.');",
- "};"
+ "// Response body should have value \"6540\" for \"amount\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/refunds - Content check if value for 'amount' matches '540'\",",
+ " function () {",
+ " pm.expect(jsonData.amount).to.eql(540);",
+ " },",
+ " );",
+ "}",
+ ""
],
"type": "text/javascript"
}
}
],
"request": {
- "method": "POST",
+ "method": "GET",
"header": [
- {
- "key": "Content-Type",
- "value": "application/json"
- },
{
"key": "Accept",
"value": "application/json"
}
],
- "body": {
- "mode": "raw",
- "options": {
- "raw": {
- "language": "json"
- }
- },
- "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"{{customer_id}}\",\"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\",\"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\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}"
- },
"url": {
- "raw": "{{baseUrl}}/payments",
+ "raw": "{{baseUrl}}/refunds/:id",
"host": [
"{{baseUrl}}"
],
"path": [
- "payments"
+ "refunds",
+ ":id"
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{refund_id}}",
+ "description": "(Required) unique refund id"
+ }
]
},
- "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ "description": "To retrieve the properties of a Refund. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
},
"response": []
- },
+ }
+ ]
+ },
+ {
+ "name": "Scenario27-Create payment without customer_id and with billing address and shipping address",
+ "item": [
{
- "name": "Save card payments - Confirm",
+ "name": "Payments - Create",
"event": [
{
"listen": "test",
"script": {
"exec": [
"// Validate status 2xx",
- "pm.test(\"[POST]::/payments/:id/confirm - Status code is 2xx\", function () {",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
" pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
- "pm.test(",
- " \"[POST]::/payments/:id/confirm - Content-Type is application/json\",",
- " function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
- " \"application/json\",",
- " );",
- " },",
- ");",
+ "pm.test(\"[POST]::/payments - 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]::/payments/:id/confirm - Response has JSON Body\", function () {",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
" pm.response.to.have.jsonBody();",
"});",
"",
@@ -20337,47 +20337,31 @@
" );",
"}",
"",
- "// Response body should have value \"adyen\" for \"connector\"",
- "if (jsonData?.connector) {",
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments/:id/confirm - Content check if value for 'connector' matches 'stripe'\",",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",",
" function () {",
- " pm.expect(jsonData.connector).to.eql(\"stripe\");",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
" },",
" );",
"}",
"",
- "// Response body should have value \"succeeded\" for \"status\"",
- "if (jsonData?.status) {",
- " pm.test(\"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'succeeded'\", function() {",
- " pm.expect(jsonData.status).to.eql(\"succeeded\");",
- " })};"
+ "// Response body should have \"connector_transaction_id\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'connector_transaction_id' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.connector_transaction_id !== \"undefined\").to.be",
+ " .true;",
+ " },",
+ ");",
+ ""
],
"type": "text/javascript"
}
}
],
"request": {
- "auth": {
- "type": "apikey",
- "apikey": [
- {
- "key": "value",
- "value": "{{publishable_key}}",
- "type": "string"
- },
- {
- "key": "key",
- "value": "api-key",
- "type": "string"
- },
- {
- "key": "in",
- "value": "header",
- "type": "string"
- }
- ]
- },
"method": "POST",
"header": [
{
@@ -20396,162 +20380,175 @@
"language": "json"
}
},
- "raw": "{\"client_secret\":\"{{client_secret}}\",\"payment_method\":\"card\",\"payment_token\":\"{{payment_token}}\"}"
+ "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"business_country\":\"US\",\"business_label\":\"default\",\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"bernard123\",\"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://duck.com\",\"setup_future_usage\":\"on_session\",\"payment_method\":\"card\",\"payment_method_type\":\"debit\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"01\",\"card_exp_year\":\"26\",\"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\":\"sundari\",\"last_name\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\",\"last_name\":\"sundari\"}},\"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/:id/confirm",
+ "raw": "{{baseUrl}}/payments",
"host": [
"{{baseUrl}}"
],
"path": [
- "payments",
- ":id",
- "confirm"
- ],
- "variable": [
- {
- "key": "id",
- "value": "{{payment_id}}",
- "description": "(Required) unique payment id"
- }
+ "payments"
]
},
- "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API"
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
},
"response": []
- }
- ]
- },
- {
- "name": "Scenario26-Save card payment with manual capture",
- "item": [
+ },
{
- "name": "Payments - Create",
+ "name": "Payments - Retrieve",
"event": [
{
"listen": "test",
"script": {
"exec": [
- "// Validate status 2xx ",
- "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
+ "// Validate status 2xx",
+ "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
- "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");",
+ "pm.test(\"[GET]::/payments/:id - 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]::/payments - Response has JSON Body\", function () {",
- " pm.response.to.have.jsonBody();",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
"});",
"",
"// Set response object as internal variable",
"let jsonData = {};",
- "try {jsonData = pm.response.json();}catch(e){}",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
"",
"// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
"if (jsonData?.payment_id) {",
- " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
- " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
"} else {",
- " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');",
- "};",
- "",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
"",
"// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
"if (jsonData?.mandate_id) {",
- " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
- " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);",
+ " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ " console.log(",
+ " \"- use {{mandate_id}} as collection variable for value\",",
+ " jsonData.mandate_id,",
+ " );",
"} else {",
- " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');",
- "};",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
+ " );",
+ "}",
"",
"// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
"if (jsonData?.client_secret) {",
- " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
- " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);",
- "} else {",
- " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');",
- "};",
- "",
- "if (jsonData?.customer_id) {",
- " pm.collectionVariables.set(\"customer_id\", jsonData.customer_id);",
- " console.log(\"- use {{customer_id}} as collection variable for value\",jsonData.customer_id);",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
"} else {",
- " console.log('INFO - Unable to assign variable {{customer_id}}, as jsonData.customer_id is undefined.');",
- "};",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
"",
- "// Response body should have value \"succeeded\" for \"status\"",
+ "// Response body should have value \"Succeeded\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",",
+ " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",",
" function () {",
" pm.expect(jsonData.status).to.eql(\"succeeded\");",
" },",
" );",
- "}"
+ "}",
+ "",
+ "// Response body should have \"connector_transaction_id\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'connector_transaction_id' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.connector_transaction_id !== \"undefined\").to.be",
+ " .true;",
+ " },",
+ ");",
+ ""
],
"type": "text/javascript"
}
}
],
"request": {
- "method": "POST",
+ "method": "GET",
"header": [
- {
- "key": "Content-Type",
- "value": "application/json"
- },
{
"key": "Accept",
"value": "application/json"
}
],
- "body": {
- "mode": "raw",
- "options": {
- "raw": {
- "language": "json"
- }
- },
- "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"adyensavecard_{{random_number}}\",\"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\",\"setup_future_usage\":\"on_session\",\"payment_method\":\"card\",\"payment_method_type\":\"credit\",\"payment_method_data\":{\"card\":{\"card_number\":\"371449635398431\",\"card_exp_month\":\"03\",\"card_exp_year\":\"2030\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"7373\"}},\"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\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}"
- },
"url": {
- "raw": "{{baseUrl}}/payments",
+ "raw": "{{baseUrl}}/payments/:id?force_sync=true",
"host": [
"{{baseUrl}}"
],
"path": [
- "payments"
+ "payments",
+ ":id"
+ ],
+ "query": [
+ {
+ "key": "force_sync",
+ "value": "true"
+ }
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
]
},
- "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
},
"response": []
- },
+ }
+ ]
+ },
+ {
+ "name": "Scenario28-Confirm a payment with requires_customer_action status",
+ "item": [
{
- "name": "Payments - Retrieve",
+ "name": "Payments - Create with confirm true",
"event": [
{
"listen": "test",
"script": {
"exec": [
"// Validate status 2xx",
- "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
" pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
- "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {",
+ "pm.test(\"[POST]::/payments - 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(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
" pm.response.to.have.jsonBody();",
"});",
"",
@@ -20600,50 +20597,24 @@
" );",
"}",
"",
- "// Response body should have value \"Succeeded\" for \"status\"",
+ "// Response body should have value \"requires_customer_action\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",",
- " function () {",
- " pm.expect(jsonData.status).to.eql(\"succeeded\");",
- " },",
- " );",
- "}",
- "",
- "// Validate the connector",
- "pm.test(\"[POST]::/payments - connector\", function () {",
- " pm.expect(jsonData.connector).to.eql(\"stripe\");",
- "});",
- "",
- "// Response body should have value \"6540\" for \"amount\"",
- "if (jsonData?.amount) {",
- " pm.test(",
- " \"[post]:://payments/:id/capture - Content check if value for 'amount' matches '6540'\",",
- " function () {",
- " pm.expect(jsonData.amount).to.eql(6540);",
- " },",
- " );",
- "}",
- "",
- "// Response body should have value \"6000\" for \"amount_received\"",
- "if (jsonData?.amount_received) {",
- " pm.test(",
- " \"[POST]::/payments:id/capture - Content check if value for 'amount_received' matches '6000'\",",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'requires_customer_action'\",",
" function () {",
- " pm.expect(jsonData.amount_received).to.eql(6540);",
+ " pm.expect(jsonData.status).to.eql(\"requires_customer_action\");",
" },",
" );",
"}",
"",
- "// Response body should have value \"6540\" for \"amount_capturable\"",
- "if (jsonData?.amount) {",
- " pm.test(",
- " \"[post]:://payments/:id/capture - Content check if value for 'amount_capturable' matches 'amount - 540'\",",
- " function () {",
- " pm.expect(jsonData.amount_capturable).to.eql(0);",
- " },",
- " );",
- "}",
+ "// Response body should have \"next_action.redirect_to_url\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'next_action.redirect_to_url' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.next_action.redirect_to_url !== \"undefined\").to.be",
+ " .true;",
+ " },",
+ ");",
""
],
"type": "text/javascript"
@@ -20651,201 +20622,250 @@
}
],
"request": {
- "method": "GET",
+ "method": "POST",
"header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
{
"key": "Accept",
"value": "application/json"
}
],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"business_country\":\"US\",\"business_label\":\"default\",\"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\",\"setup_future_usage\":\"on_session\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4000000000003063\",\"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\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\"}},\"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/:id?force_sync=true",
+ "raw": "{{baseUrl}}/payments",
"host": [
"{{baseUrl}}"
],
"path": [
- "payments",
- ":id"
- ],
- "query": [
- {
- "key": "force_sync",
- "value": "true"
- }
- ],
- "variable": [
- {
- "key": "id",
- "value": "{{payment_id}}",
- "description": "(Required) unique payment id"
- }
+ "payments"
]
},
- "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
},
"response": []
},
{
- "name": "List payment methods for a Customer",
+ "name": "Payments - Confirm",
"event": [
{
"listen": "test",
"script": {
"exec": [
- "// Validate status 2xx ",
- "pm.test(\"[GET]::/payment_methods/:customer_id - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
+ "// Validate status 2xx",
+ "pm.test(\"[GET]::/payments/:id - Status code is 400\", function () {",
+ " pm.response.to.be.error;",
"});",
"",
"// Validate if response header has matching content-type",
- "pm.test(\"[GET]::/payment_methods/:customer_id - Content-Type is application/json\", function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");",
+ "pm.test(\"[GET]::/payments/:id - 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(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
"});",
"",
"// Set response object as internal variable",
"let jsonData = {};",
- "try {jsonData = pm.response.json();}catch(e){}",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) { }",
"",
- "if (jsonData?.customer_payment_methods[0]?.payment_token) {",
- " pm.collectionVariables.set(\"payment_token\", jsonData.customer_payment_methods[0].payment_token);",
- " console.log(\"- use {{payment_token}} as collection variable for value\", jsonData.customer_payment_methods[0].payment_token);",
- "} else {",
- " console.log('INFO - Unable to assign variable {{payment_token}}, as jsonData.customer_payment_methods[0].payment_token is undefined.');",
- "}"
+ "",
+ "// Response body should have appropriatae error message",
+ "if (jsonData?.message) {",
+ " pm.test(",
+ " \"Content check if appropriate error message is present\",",
+ " function () {",
+ " pm.expect(jsonData.message).to.eql(\"You cannot confirm this payment because it has status requires_customer_action\");",
+ " },",
+ " );",
+ "}",
+ ""
],
"type": "text/javascript"
}
}
],
"request": {
- "method": "GET",
- "header": [
- {
- "key": "Accept",
- "value": "application/json"
- }
- ],
- "url": {
- "raw": "{{baseUrl}}/customers/:customer_id/payment_methods",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "customers",
- ":customer_id",
- "payment_methods"
- ],
- "query": [
- {
- "key": "accepted_country",
- "value": "co",
- "disabled": true
- },
- {
- "key": "accepted_country",
- "value": "pa",
- "disabled": true
- },
- {
- "key": "accepted_currency",
- "value": "voluptate ea",
- "disabled": true
- },
- {
- "key": "accepted_currency",
- "value": "exercitation",
- "disabled": true
- },
- {
- "key": "minimum_amount",
- "value": "100",
- "disabled": true
- },
+ "auth": {
+ "type": "apikey",
+ "apikey": [
{
- "key": "maximum_amount",
- "value": "10000000",
- "disabled": true
+ "key": "value",
+ "value": "{{publishable_key}}",
+ "type": "string"
},
{
- "key": "recurring_payment_enabled",
- "value": "true",
- "disabled": true
+ "key": "key",
+ "value": "api-key",
+ "type": "string"
},
{
- "key": "installment_payment_enabled",
- "value": "true",
- "disabled": true
+ "key": "in",
+ "value": "header",
+ "type": "string"
+ }
+ ]
+ },
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
}
+ },
+ "raw": "{\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"Joseph Doe\",\"card_cvc\":\"123\"}},\"client_secret\":\"{{client_secret}}\",\"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\":\"125.0.0.1\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id/confirm",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id",
+ "confirm"
],
"variable": [
{
- "key": "customer_id",
- "value": "{{customer_id}}",
- "description": "//Pass the customer id"
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
}
]
},
- "description": "To filter and list the applicable payment methods for a particular Customer ID"
+ "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API"
},
"response": []
- },
+ }
+ ]
+ },
+ {
+ "name": "Scenario29-Create payment with payment method billing",
+ "item": [
{
- "name": "Save card payments - Create",
+ "name": "Payments - Create",
"event": [
{
"listen": "test",
"script": {
"exec": [
- "// Validate status 2xx ",
+ "// Validate status 2xx",
"pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
+ " pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
"pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(\"application/json\");",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
"});",
"",
- "// Validate if response has JSON Body ",
+ "// Validate if response has JSON Body",
"pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
- " pm.response.to.have.jsonBody();",
+ " pm.response.to.have.jsonBody();",
"});",
"",
"// Set response object as internal variable",
"let jsonData = {};",
- "try {jsonData = pm.response.json();}catch(e){}",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) { }",
"",
"// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
"if (jsonData?.payment_id) {",
- " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
- " console.log(\"- use {{payment_id}} as collection variable for value\",jsonData.payment_id);",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
"} else {",
- " console.log('INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.');",
- "};",
- "",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
"",
"// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
"if (jsonData?.mandate_id) {",
- " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
- " console.log(\"- use {{mandate_id}} as collection variable for value\",jsonData.mandate_id);",
+ " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ " console.log(",
+ " \"- use {{mandate_id}} as collection variable for value\",",
+ " jsonData.mandate_id,",
+ " );",
"} else {",
- " console.log('INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.');",
- "};",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
+ " );",
+ "}",
"",
"// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
"if (jsonData?.client_secret) {",
- " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
- " console.log(\"- use {{client_secret}} as collection variable for value\",jsonData.client_secret);",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
"} else {",
- " console.log('INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.');",
- "};",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
"",
- "if (jsonData?.customer_id) {",
- " pm.collectionVariables.set(\"customer_id\", jsonData.customer_id);",
- " console.log(\"- use {{customer_id}} as collection variable for value\",jsonData.customer_id);",
- "} else {",
- " console.log('INFO - Unable to assign variable {{customer_id}}, as jsonData.customer_id is undefined.');",
- "};"
+ "// Response body should have value \"succeeded\" for \"status\"",
+ "if (jsonData?.status) {",
+ " pm.test(",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",",
+ " function () {",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
+ " },",
+ " );",
+ "}",
+ "",
+ "// Response body should have \"connector_transaction_id\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'connector_transaction_id' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.connector_transaction_id !== \"undefined\").to.be",
+ " .true;",
+ " },",
+ ");",
+ "",
+ "// Response body should have \"payment_method_data.billing\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'payment_method_data.billing' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.payment_method_data.billing !== \"undefined\").to.be",
+ " .true;",
+ " },",
+ ");",
+ ""
],
"type": "text/javascript"
}
@@ -20870,7 +20890,7 @@
"language": "json"
}
},
- "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"manual\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"{{customer_id}}\",\"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\",\"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\"},\"routing\":{\"type\":\"single\",\"data\":\"stripe\"}}"
+ "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"business_country\":\"US\",\"business_label\":\"default\",\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"bernard123\",\"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://duck.com\",\"setup_future_usage\":\"on_session\",\"payment_method\":\"card\",\"payment_method_type\":\"debit\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"01\",\"card_exp_year\":\"26\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrisoff Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"Narayan\",\"last_name\":\"Doe\"},\"email\":\"example@juspay.in\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\",\"last_name\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\",\"last_name\":\"sundari\"}},\"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",
@@ -20886,29 +20906,26 @@
"response": []
},
{
- "name": "Save card payments - Confirm",
+ "name": "Payments - Retrieve",
"event": [
{
"listen": "test",
"script": {
"exec": [
"// Validate status 2xx",
- "pm.test(\"[POST]::/payments/:id/confirm - Status code is 2xx\", function () {",
+ "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
" pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
- "pm.test(",
- " \"[POST]::/payments/:id/confirm - Content-Type is application/json\",",
- " function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
- " \"application/json\",",
- " );",
- " },",
- ");",
+ "pm.test(\"[GET]::/payments/:id - 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]::/payments/:id/confirm - Response has JSON Body\", function () {",
+ "pm.test(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
" pm.response.to.have.jsonBody();",
"});",
"",
@@ -20916,7 +20933,7 @@
"let jsonData = {};",
"try {",
" jsonData = pm.response.json();",
- "} catch (e) {}",
+ "} catch (e) { }",
"",
"// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
"if (jsonData?.payment_id) {",
@@ -20957,26 +20974,33 @@
" );",
"}",
"",
- "// Response body should have value \"requires_capture\" for \"status\"",
+ "// Response body should have value \"Succeeded\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'requires_capture'\",",
+ " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",",
" function () {",
- " pm.expect(jsonData.status).to.eql(\"requires_capture\");",
+ " pm.expect(jsonData.status).to.eql(\"succeeded\");",
" },",
" );",
"}",
"",
+ "// Response body should have \"connector_transaction_id\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'connector_transaction_id' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.connector_transaction_id !== \"undefined\").to.be",
+ " .true;",
+ " },",
+ ");",
"",
- "// Response body should have value \"stripe\" for \"connector\"",
- "if (jsonData?.connector) {",
- " pm.test(",
- " \"[POST]::/payments/:id/confirm - Content check if value for 'connector' matches 'stripe'\",",
- " function () {",
- " pm.expect(jsonData.connector).to.eql(\"stripe\");",
- " },",
- " );",
- "}",
+ "// Response body should have \"payment_method_data.billing\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'payment_method_data.billing' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.payment_method_data.billing !== \"undefined\").to.be",
+ " .true;",
+ " },",
+ ");",
""
],
"type": "text/javascript"
@@ -20984,55 +21008,27 @@
}
],
"request": {
- "auth": {
- "type": "apikey",
- "apikey": [
- {
- "key": "value",
- "value": "{{publishable_key}}",
- "type": "string"
- },
- {
- "key": "key",
- "value": "api-key",
- "type": "string"
- },
- {
- "key": "in",
- "value": "header",
- "type": "string"
- }
- ]
- },
- "method": "POST",
+ "method": "GET",
"header": [
- {
- "key": "Content-Type",
- "value": "application/json"
- },
{
"key": "Accept",
"value": "application/json"
}
],
- "body": {
- "mode": "raw",
- "options": {
- "raw": {
- "language": "json"
- }
- },
- "raw": "{\"client_secret\":\"{{client_secret}}\",\"payment_method\":\"card\",\"payment_token\":\"{{payment_token}}\",\"card_cvc\":\"7373\"}"
- },
"url": {
- "raw": "{{baseUrl}}/payments/:id/confirm",
+ "raw": "{{baseUrl}}/payments/:id?force_sync=true",
"host": [
"{{baseUrl}}"
],
"path": [
"payments",
- ":id",
- "confirm"
+ ":id"
+ ],
+ "query": [
+ {
+ "key": "force_sync",
+ "value": "true"
+ }
],
"variable": [
{
@@ -21042,34 +21038,36 @@
}
]
},
- "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API"
+ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
},
"response": []
- },
+ }
+ ]
+ },
+ {
+ "name": "Scenario30-Update payment with payment method billing",
+ "item": [
{
- "name": "Payments - Capture",
+ "name": "Payments - Create",
"event": [
{
"listen": "test",
"script": {
"exec": [
"// Validate status 2xx",
- "pm.test(\"[POST]::/payments/:id/capture - Status code is 2xx\", function () {",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
" pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
- "pm.test(",
- " \"[POST]::/payments/:id/capture - Content-Type is application/json\",",
- " function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
- " \"application/json\",",
- " );",
- " },",
- ");",
+ "pm.test(\"[POST]::/payments - 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]::/payments/:id/capture - Response has JSON Body\", function () {",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
" pm.response.to.have.jsonBody();",
"});",
"",
@@ -21077,7 +21075,7 @@
"let jsonData = {};",
"try {",
" jsonData = pm.response.json();",
- "} catch (e) {}",
+ "} catch (e) { }",
"",
"// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
"if (jsonData?.payment_id) {",
@@ -21092,19 +21090,6 @@
" );",
"}",
"",
- "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
- "if (jsonData?.mandate_id) {",
- " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
- " console.log(",
- " \"- use {{mandate_id}} as collection variable for value\",",
- " jsonData.mandate_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
- " );",
- "}",
- "",
"// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
"if (jsonData?.client_secret) {",
" pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
@@ -21118,47 +21103,12 @@
" );",
"}",
"",
- "// Response body should have value \"succeeded\" for \"status\"",
+ "// Response body should have value \"requires_payment_method\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]:://payments/:id/capture - Content check if value for 'status' matches 'succeeded'\",",
- " function () {",
- " pm.expect(jsonData.status).to.eql(\"succeeded\");",
- " },",
- " );",
- "}",
- "",
- "// Validate the connector",
- "pm.test(\"[POST]::/payments - connector\", function () {",
- " pm.expect(jsonData.connector).to.eql(\"stripe\");",
- "});",
- "",
- "// Response body should have value \"6540\" for \"amount\"",
- "if (jsonData?.amount) {",
- " pm.test(",
- " \"[post]:://payments/:id/capture - Content check if value for 'amount' matches '6540'\",",
- " function () {",
- " pm.expect(jsonData.amount).to.eql(6540);",
- " },",
- " );",
- "}",
- "",
- "// Response body should have value \"6000\" for \"amount_received\"",
- "if (jsonData?.amount_received) {",
- " pm.test(",
- " \"[POST]::/payments:id/capture - Content check if value for 'amount_received' matches '6540'\",",
- " function () {",
- " pm.expect(jsonData.amount_received).to.eql(6540);",
- " },",
- " );",
- "}",
- "",
- "// Response body should have value \"6540\" for \"amount_capturable\"",
- "if (jsonData?.amount_capturable) {",
- " pm.test(",
- " \"[post]:://payments/:id/capture - Content check if value for 'amount_capturable' matches 'amount - 540'\",",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'\",",
" function () {",
- " pm.expect(jsonData.amount_capturable).to.eql(6540);",
+ " pm.expect(jsonData.status).to.eql(\"requires_payment_method\");",
" },",
" );",
"}",
@@ -21187,51 +21137,42 @@
"language": "json"
}
},
- "raw": "{\"amount_to_capture\":6540,\"statement_descriptor_name\":\"Joseph\",\"statement_descriptor_suffix\":\"JS\"}"
+ "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":false,\"business_country\":\"US\",\"business_label\":\"default\",\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"bernard123\",\"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://duck.com\",\"setup_future_usage\":\"on_session\",\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\",\"last_name\":\"sundari\"}},\"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/:id/capture",
+ "raw": "{{baseUrl}}/payments",
"host": [
"{{baseUrl}}"
],
"path": [
- "payments",
- ":id",
- "capture"
- ],
- "variable": [
- {
- "key": "id",
- "value": "{{payment_id}}",
- "description": "(Required) unique payment id"
- }
+ "payments"
]
},
- "description": "To capture the funds for an uncaptured payment"
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
},
"response": []
},
{
- "name": "Payments - Retrieve-copy",
+ "name": "Payments - Update",
"event": [
{
"listen": "test",
"script": {
"exec": [
"// Validate status 2xx",
- "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
" pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
- "pm.test(\"[GET]::/payments/:id - Content-Type is application/json\", function () {",
+ "pm.test(\"[POST]::/payments - 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(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
" pm.response.to.have.jsonBody();",
"});",
"",
@@ -21239,91 +21180,26 @@
"let jsonData = {};",
"try {",
" jsonData = pm.response.json();",
- "} catch (e) {}",
- "",
- "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
- "if (jsonData?.payment_id) {",
- " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
- " console.log(",
- " \"- use {{payment_id}} as collection variable for value\",",
- " jsonData.payment_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
- " );",
- "}",
- "",
- "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
- "if (jsonData?.mandate_id) {",
- " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
- " console.log(",
- " \"- use {{mandate_id}} as collection variable for value\",",
- " jsonData.mandate_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
- " );",
- "}",
- "",
- "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
- "if (jsonData?.client_secret) {",
- " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
- " console.log(",
- " \"- use {{client_secret}} as collection variable for value\",",
- " jsonData.client_secret,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
- " );",
- "}",
+ "} catch (e) { }",
"",
- "// Response body should have value \"Succeeded\" for \"status\"",
+ "// Response body should have value \"requires_confirmation\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",",
- " function () {",
- " pm.expect(jsonData.status).to.eql(\"succeeded\");",
- " },",
- " );",
- "}",
- "",
- "// Validate the connector",
- "pm.test(\"[POST]::/payments - connector\", function () {",
- " pm.expect(jsonData.connector).to.eql(\"stripe\");",
- "});",
- "",
- "// Response body should have value \"6540\" for \"amount\"",
- "if (jsonData?.amount) {",
- " pm.test(",
- " \"[post]:://payments/:id/capture - Content check if value for 'amount' matches '6540'\",",
- " function () {",
- " pm.expect(jsonData.amount).to.eql(6540);",
- " },",
- " );",
- "}",
- "",
- "// Response body should have value \"6000\" for \"amount_received\"",
- "if (jsonData?.amount_received) {",
- " pm.test(",
- " \"[POST]::/payments:id/capture - Content check if value for 'amount_received' matches '6540'\",",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'\",",
" function () {",
- " pm.expect(jsonData.amount_received).to.eql(6540);",
+ " pm.expect(jsonData.status).to.eql(\"requires_confirmation\");",
" },",
" );",
"}",
"",
- "// Response body should have value \"6540\" for \"amount_capturable\"",
- "if (jsonData?.amount) {",
- " pm.test(",
- " \"[post]:://payments/:id/capture - Content check if value for 'amount_capturable' matches 'amount - 540'\",",
- " function () {",
- " pm.expect(jsonData.amount_capturable).to.eql(0);",
- " },",
- " );",
- "}",
+ "// Response body should have \"payment_method_data.billing\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'payment_method_data.billing' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.payment_method_data.billing !== \"undefined\").to.be",
+ " .true;",
+ " },",
+ ");",
""
],
"type": "text/javascript"
@@ -21331,15 +21207,28 @@
}
],
"request": {
- "method": "GET",
+ "method": "POST",
"header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
{
"key": "Accept",
"value": "application/json"
}
],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"01\",\"card_exp_year\":\"26\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrisoff Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"Narayan\",\"last_name\":\"Doe\"},\"email\":\"example@juspay.in\"}}}"
+ },
"url": {
- "raw": "{{baseUrl}}/payments/:id?force_sync=true",
+ "raw": "{{baseUrl}}/payments/:id",
"host": [
"{{baseUrl}}"
],
@@ -21347,86 +21236,104 @@
"payments",
":id"
],
- "query": [
- {
- "key": "force_sync",
- "value": "true"
- }
- ],
"variable": [
{
"key": "id",
- "value": "{{payment_id}}",
- "description": "(Required) unique payment id"
+ "value": "{{payment_id}}"
}
]
},
- "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
},
"response": []
},
{
- "name": "Refunds - Create Copy",
+ "name": "Payments - Retrieve",
"event": [
{
"listen": "test",
"script": {
"exec": [
"// Validate status 2xx",
- "pm.test(\"[POST]::/refunds - Status code is 2xx\", function () {",
+ "pm.test(\"[GET]::/payments/:id - Status code is 2xx\", function () {",
" pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
- "pm.test(\"[POST]::/refunds - Content-Type is application/json\", function () {",
+ "pm.test(\"[GET]::/payments/:id - 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(\"[GET]::/payments/:id - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
"// Set response object as internal variable",
"let jsonData = {};",
"try {",
" jsonData = pm.response.json();",
- "} catch (e) {}",
+ "} catch (e) { }",
"",
- "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id",
- "if (jsonData?.refund_id) {",
- " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
" console.log(",
- " \"- use {{refund_id}} as collection variable for value\",",
- " jsonData.refund_id,",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
" );",
"} else {",
" console.log(",
- " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
" );",
"}",
"",
- "// Response body should have value \"succeeded\" for \"status\"",
- "if (jsonData?.status) {",
- " pm.test(",
- " \"[POST]::/refunds - Content check if value for 'status' matches 'succeeded'\",",
- " function () {",
- " pm.expect(jsonData.status).to.eql(\"succeeded\");",
- " },",
+ "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
+ "if (jsonData?.mandate_id) {",
+ " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ " console.log(",
+ " \"- use {{mandate_id}} as collection variable for value\",",
+ " jsonData.mandate_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
" );",
"}",
"",
- "// Response body should have value \"540\" for \"amount\"",
+ "// Response body should have value \"requires_confirmation\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/refunds - Content check if value for 'amount' matches '540'\",",
+ " \"[POST]::/payments/:id - Content check if value for 'status' matches 'requires_confirmation'\",",
" function () {",
- " pm.expect(jsonData.amount).to.eql(540);",
+ " pm.expect(jsonData.status).to.eql(\"requires_confirmation\");",
" },",
" );",
"}",
"",
- "// Validate the connector",
- "pm.test(\"[POST]::/payments - connector\", function () {",
- " pm.expect(jsonData.connector).to.eql(\"stripe\");",
- "});",
+ "// Response body should have \"payment_method_data.billing\"",
+ "pm.test(",
+ " \"[POST]::/payments - Content check if 'payment_method_data.billing' exists\",",
+ " function () {",
+ " pm.expect(typeof jsonData.payment_method_data.billing !== \"undefined\").to.be",
+ " .true;",
+ " },",
+ ");",
""
],
"type": "text/javascript"
@@ -21434,93 +21341,120 @@
}
],
"request": {
- "method": "POST",
+ "method": "GET",
"header": [
- {
- "key": "Content-Type",
- "value": "application/json"
- },
{
"key": "Accept",
"value": "application/json"
}
],
- "body": {
- "mode": "raw",
- "options": {
- "raw": {
- "language": "json"
- }
- },
- "raw": "{\"payment_id\":\"{{payment_id}}\",\"amount\":540,\"reason\":\"Customer returned product\",\"refund_type\":\"instant\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
- },
"url": {
- "raw": "{{baseUrl}}/refunds",
+ "raw": "{{baseUrl}}/payments/:id?force_sync=true",
"host": [
"{{baseUrl}}"
],
"path": [
- "refunds"
+ "payments",
+ ":id"
+ ],
+ "query": [
+ {
+ "key": "force_sync",
+ "value": "true"
+ }
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
]
},
- "description": "To create a refund against an already processed payment"
+ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
},
"response": []
- },
+ }
+ ]
+ },
+ {
+ "name": "Scenario31-Pass payment method billing in Confirm",
+ "item": [
{
- "name": "Refunds - Retrieve Copy",
+ "name": "Payments - Create",
"event": [
{
"listen": "test",
"script": {
"exec": [
"// Validate status 2xx",
- "pm.test(\"[GET]::/refunds/:id - Status code is 2xx\", function () {",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
" pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
- "pm.test(\"[GET]::/refunds/:id - Content-Type is application/json\", function () {",
+ "pm.test(\"[POST]::/payments - 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]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
"// Set response object as internal variable",
"let jsonData = {};",
"try {",
" jsonData = pm.response.json();",
"} catch (e) {}",
"",
- "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id",
- "if (jsonData?.refund_id) {",
- " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
" console.log(",
- " \"- use {{refund_id}} as collection variable for value\",",
- " jsonData.refund_id,",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
" );",
"} else {",
" console.log(",
- " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
" );",
"}",
"",
- "// Response body should have value \"succeeded\" for \"status\"",
- "if (jsonData?.status) {",
- " pm.test(",
- " \"[POST]::/refunds - Content check if value for 'status' matches 'succeeded'\",",
- " function () {",
- " pm.expect(jsonData.status).to.eql(\"succeeded\");",
- " },",
+ "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
+ "if (jsonData?.mandate_id) {",
+ " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ " console.log(",
+ " \"- use {{mandate_id}} as collection variable for value\",",
+ " jsonData.mandate_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
" );",
"}",
"",
- "// Response body should have value \"6540\" for \"amount\"",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// Response body should have value \"requires_payment_method\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/refunds - Content check if value for 'amount' matches '540'\",",
+ " \"[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'\",",
" function () {",
- " pm.expect(jsonData.amount).to.eql(540);",
+ " pm.expect(jsonData.status).to.eql(\"requires_payment_method\");",
" },",
" );",
"}",
@@ -21528,63 +21462,75 @@
],
"type": "text/javascript"
}
+ },
+ {
+ "listen": "prerequest",
+ "script": {
+ "exec": [
+ ""
+ ],
+ "type": "text/javascript"
+ }
}
],
"request": {
- "method": "GET",
+ "method": "POST",
"header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
{
"key": "Accept",
"value": "application/json"
}
],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "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://duck.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"PiX\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"PiX\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}"
+ },
"url": {
- "raw": "{{baseUrl}}/refunds/:id",
+ "raw": "{{baseUrl}}/payments",
"host": [
"{{baseUrl}}"
],
"path": [
- "refunds",
- ":id"
- ],
- "variable": [
- {
- "key": "id",
- "value": "{{refund_id}}",
- "description": "(Required) unique refund id"
- }
+ "payments"
]
},
- "description": "To retrieve the properties of a Refund. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
},
"response": []
- }
- ]
- },
- {
- "name": "Scenario27-Create payment without customer_id and with billing address and shipping address",
- "item": [
+ },
{
- "name": "Payments - Create",
+ "name": "Payments - Confirm",
"event": [
{
"listen": "test",
"script": {
"exec": [
"// Validate status 2xx",
- "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ "pm.test(\"[POST]::/payments/:id/confirm - Status code is 2xx\", function () {",
" pm.response.to.be.success;",
"});",
"",
"// Validate if response header has matching content-type",
- "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
- " \"application/json\",",
- " );",
- "});",
+ "pm.test(",
+ " \"[POST]::/payments/:id/confirm - 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]::/payments - Response has JSON Body\", function () {",
+ "pm.test(\"[POST]::/payments/:id/confirm - Response has JSON Body\", function () {",
" pm.response.to.have.jsonBody();",
"});",
"",
@@ -21636,21 +21582,21 @@
"// Response body should have value \"succeeded\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments - Content check if value for 'status' matches 'succeeded'\",",
+ " \"[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'succeeded'\",",
" function () {",
" pm.expect(jsonData.status).to.eql(\"succeeded\");",
" },",
" );",
"}",
- "",
- "// Response body should have \"connector_transaction_id\"",
- "pm.test(",
- " \"[POST]::/payments - Content check if 'connector_transaction_id' exists\",",
- " function () {",
- " pm.expect(typeof jsonData.connector_transaction_id !== \"undefined\").to.be",
- " .true;",
- " },",
- ");",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ },
+ {
+ "listen": "prerequest",
+ "script": {
+ "exec": [
""
],
"type": "text/javascript"
@@ -21658,6 +21604,26 @@
}
],
"request": {
+ "auth": {
+ "type": "apikey",
+ "apikey": [
+ {
+ "key": "value",
+ "value": "{{publishable_key}}",
+ "type": "string"
+ },
+ {
+ "key": "key",
+ "value": "api-key",
+ "type": "string"
+ },
+ {
+ "key": "in",
+ "value": "header",
+ "type": "string"
+ }
+ ]
+ },
"method": "POST",
"header": [
{
@@ -21676,18 +21642,27 @@
"language": "json"
}
},
- "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":true,\"business_country\":\"US\",\"business_label\":\"default\",\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":6540,\"customer_id\":\"bernard123\",\"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://duck.com\",\"setup_future_usage\":\"on_session\",\"payment_method\":\"card\",\"payment_method_type\":\"debit\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"01\",\"card_exp_year\":\"26\",\"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\":\"sundari\",\"last_name\":\"sundari\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"sundari\",\"last_name\":\"sundari\"}},\"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": "{\"payment_method\":\"card\",\"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\":\"Harrisoff Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"Narayan\",\"last_name\":\"Doe\"},\"email\":\"example@juspay.in\"}},\"client_secret\":\"{{client_secret}}\",\"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\":\"125.0.0.1\"}}"
},
"url": {
- "raw": "{{baseUrl}}/payments",
+ "raw": "{{baseUrl}}/payments/:id/confirm",
"host": [
"{{baseUrl}}"
],
"path": [
- "payments"
+ "payments",
+ ":id",
+ "confirm"
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
]
},
- "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API"
},
"response": []
},
@@ -21719,7 +21694,7 @@
"let jsonData = {};",
"try {",
" jsonData = pm.response.json();",
- "} catch (e) {}",
+ "} catch (e) { }",
"",
"// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
"if (jsonData?.payment_id) {",
@@ -21760,21 +21735,21 @@
" );",
"}",
"",
- "// Response body should have value \"Succeeded\" for \"status\"",
+ "// Response body should have value \"succeeded\" for \"status\"",
"if (jsonData?.status) {",
" pm.test(",
- " \"[POST]::/payments/:id - Content check if value for 'status' matches 'succeeded'\",",
+ " \"[POST]::/payments:id - Content check if value for 'status' matches 'succeeded'\",",
" function () {",
" pm.expect(jsonData.status).to.eql(\"succeeded\");",
" },",
" );",
"}",
"",
- "// Response body should have \"connector_transaction_id\"",
+ "// Response body should have \"payment_method_data.billing\"",
"pm.test(",
- " \"[POST]::/payments - Content check if 'connector_transaction_id' exists\",",
+ " \"[POST]::/payments - Content check if 'payment_method_data.billing' exists\",",
" function () {",
- " pm.expect(typeof jsonData.connector_transaction_id !== \"undefined\").to.be",
+ " pm.expect(typeof jsonData.payment_method_data.billing !== \"undefined\").to.be",
" .true;",
" },",
");",
|
2024-03-05T04:09:55Z
|
## 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 PR is a fix for postman CI failing due a bug introduced in https://github.com/juspay/hyperswitch/pull/3807.
As we can see here in CI's commit, https://github.com/juspay/hyperswitch/commit/cd7040fa8cad2e69a53e3ed609c9eb8a8a17495a, it is clear that NMI and Stripe collection are the ones that are affected which again can be confirmed with https://github.com/juspay/hyperswitch/actions/runs/8148897592/job/22272607599
Closes #3955
### 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).
-->
People are shouting that the collections are failing. We've to keep them calm.
## 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)?
-->
NMI
<img width="478" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/0f1aa4d9-5bf2-4014-9b5d-00ac992ead9e">
Stripe
<img width="491" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/4c8a2d3b-cd5e-41de-b4aa-d91dc9f00149">
## Checklist
<!-- Put an `x` in the boxes that apply -->
- [ ] 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
2b0fbc70749338d5c501bbb782d6fc4747890d61
|
|
juspay/hyperswitch
|
juspay__hyperswitch-3911
|
Bug: [FEATURE] : Add `WASM` support for `endpoint_prefix` in dashboard
### Feature Description
Add WASM configs for dashboard to take `endpoint_prefix` as input for Adyen Connector Create.
### Possible Implementation
Add WASM configs for dashboard to take `endpoint_prefix` as input for Adyen Connector Create.
### 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/src/common_config.rs b/crates/connector_configs/src/common_config.rs
index c3cbaab4ab3..2af5b88b337 100644
--- a/crates/connector_configs/src/common_config.rs
+++ b/crates/connector_configs/src/common_config.rs
@@ -81,6 +81,7 @@ pub struct ApiModelMetaData {
pub google_pay: Option<GoogleApiModelData>,
pub apple_pay: Option<ApplePayData>,
pub apple_pay_combined: Option<ApplePayData>,
+ pub endpoint_prefix: Option<String>,
}
#[serde_with::skip_serializing_none]
@@ -173,4 +174,5 @@ pub struct DashboardMetaData {
pub google_pay: Option<GooglePayData>,
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 f0997d53107..357ee0cb73f 100644
--- a/crates/connector_configs/src/connector.rs
+++ b/crates/connector_configs/src/connector.rs
@@ -74,6 +74,7 @@ pub struct ConfigMetadata {
pub google_pay: Option<GooglePayData>,
pub apple_pay: Option<ApplePayTomlConfig>,
pub merchant_id: Option<String>,
+ pub endpoint_prefix: Option<String>,
}
#[serde_with::skip_serializing_none]
diff --git a/crates/connector_configs/src/response_modifier.rs b/crates/connector_configs/src/response_modifier.rs
index 80332612c13..5942a9e01ae 100644
--- a/crates/connector_configs/src/response_modifier.rs
+++ b/crates/connector_configs/src/response_modifier.rs
@@ -293,6 +293,10 @@ impl ConnectorApiIntegrationPayload {
Some(meta_data) => meta_data.terminal_id,
_ => None,
};
+ let endpoint_prefix = match response.metadata.clone() {
+ Some(meta_data) => meta_data.endpoint_prefix,
+ _ => None,
+ };
let apple_pay = match response.metadata.clone() {
Some(meta_data) => meta_data.apple_pay,
_ => None,
@@ -315,6 +319,7 @@ impl ConnectorApiIntegrationPayload {
account_name,
terminal_id,
merchant_id,
+ endpoint_prefix,
};
DashboardRequestPayload {
diff --git a/crates/connector_configs/src/transformer.rs b/crates/connector_configs/src/transformer.rs
index be68a0c5f94..735178cd676 100644
--- a/crates/connector_configs/src/transformer.rs
+++ b/crates/connector_configs/src/transformer.rs
@@ -186,6 +186,7 @@ impl DashboardRequestPayload {
merchant_account_id: None,
merchant_id: None,
merchant_config_currency: None,
+ endpoint_prefix: None,
};
let meta_data = match request.metadata {
Some(data) => data,
@@ -196,6 +197,7 @@ impl DashboardRequestPayload {
let merchant_account_id = meta_data.merchant_account_id.clone();
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 apple_pay = meta_data.apple_pay;
let apple_pay_combined = meta_data.apple_pay_combined;
let merchant_config_currency = meta_data.merchant_config_currency;
@@ -208,6 +210,7 @@ impl DashboardRequestPayload {
merchant_id,
merchant_config_currency,
apple_pay_combined,
+ endpoint_prefix,
})
}
diff --git a/crates/diesel_models/src/enums.rs b/crates/diesel_models/src/enums.rs
index a616f302cfc..0310944de7e 100644
--- a/crates/diesel_models/src/enums.rs
+++ b/crates/diesel_models/src/enums.rs
@@ -372,6 +372,9 @@ pub enum BankNames {
TsbBank,
TescoBank,
UlsterBank,
+ Yoursafe,
+ N26,
+ NationaleNederlanden,
}
#[derive(
diff --git a/crates/router/src/connector/adyen.rs b/crates/router/src/connector/adyen.rs
index 261495e2bfa..93301364e62 100644
--- a/crates/router/src/connector/adyen.rs
+++ b/crates/router/src/connector/adyen.rs
@@ -280,10 +280,12 @@ fn build_env_specific_endpoint(
} else {
let adyen_connector_metadata_object =
transformers::AdyenConnectorMetadataObject::try_from(connector_metadata)?;
- Ok(base_url.replace(
- "{{merchant_endpoint_prefix}}",
- &adyen_connector_metadata_object.endpoint_prefix,
- ))
+ let endpoint_prefix = adyen_connector_metadata_object.endpoint_prefix.ok_or(
+ errors::ConnectorError::InvalidConnectorConfig {
+ config: "metadata.endpoint_prefix",
+ },
+ )?;
+ Ok(base_url.replace("{{merchant_endpoint_prefix}}", &endpoint_prefix))
}
}
@@ -1556,17 +1558,6 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref
impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData>
for Adyen
{
- fn build_request(
- &self,
- _req: &types::RefundsRouterData<api::RSync>,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- Err(errors::ConnectorError::FlowNotSupported {
- flow: "Rsync".to_owned(),
- connector: "Adyen".to_owned(),
- }
- .into())
- }
}
fn get_webhook_object_from_body(
diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs
index 7f20041e1fc..9fbf7d99812 100644
--- a/crates/router/src/connector/adyen/transformers.rs
+++ b/crates/router/src/connector/adyen/transformers.rs
@@ -63,7 +63,7 @@ impl<T>
}
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct AdyenConnectorMetadataObject {
- pub endpoint_prefix: String,
+ pub endpoint_prefix: Option<String>,
}
impl TryFrom<&Option<pii::SecretSerdeValue>> for AdyenConnectorMetadataObject {
@@ -106,7 +106,8 @@ pub enum AuthType {
#[serde(rename_all = "camelCase")]
pub struct AdditionalData {
authorisation_type: Option<AuthType>,
- manual_capture: Option<bool>,
+ manual_capture: Option<String>,
+ execute_three_d: Option<String>,
pub recurring_processing_model: Option<AdyenRecurringModel>,
/// Enable recurring details in dashboard to receive this ID, https://docs.adyen.com/online-payments/tokenization/create-and-use-tokens#test-and-go-live
#[serde(rename = "recurring.recurringDetailReference")]
@@ -1641,19 +1642,28 @@ fn get_browser_info(
}
fn get_additional_data(item: &types::PaymentsAuthorizeRouterData) -> Option<AdditionalData> {
- match item.request.capture_method {
+ let (authorisation_type, manual_capture) = match item.request.capture_method {
Some(diesel_models::enums::CaptureMethod::Manual)
- | Some(diesel_models::enums::CaptureMethod::ManualMultiple) => Some(AdditionalData {
- authorisation_type: Some(AuthType::PreAuth),
- manual_capture: Some(true),
- network_tx_reference: None,
- recurring_detail_reference: None,
- recurring_shopper_reference: None,
- recurring_processing_model: Some(AdyenRecurringModel::UnscheduledCardOnFile),
- ..AdditionalData::default()
- }),
- _ => None,
- }
+ | Some(diesel_models::enums::CaptureMethod::ManualMultiple) => {
+ (Some(AuthType::PreAuth), Some("true".to_string()))
+ }
+ _ => (None, None),
+ };
+ let execute_three_d = if matches!(item.auth_type, enums::AuthenticationType::ThreeDs) {
+ Some("true".to_string())
+ } else {
+ None
+ };
+ Some(AdditionalData {
+ authorisation_type,
+ manual_capture,
+ execute_three_d,
+ network_tx_reference: None,
+ recurring_detail_reference: None,
+ recurring_shopper_reference: None,
+ recurring_processing_model: None,
+ ..AdditionalData::default()
+ })
}
fn get_channel_type(pm_type: &Option<storage_enums::PaymentMethodType>) -> Option<Channel> {
@@ -3809,7 +3819,7 @@ impl<F> TryFrom<types::RefundsResponseRouterData<F, AdyenRefundResponse>>
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(types::RefundsResponseData {
- connector_refund_id: item.response.reference,
+ connector_refund_id: item.response.psp_reference,
// From the docs, the only value returned is "received", outcome of refund is available
// through refund notification webhook
// For more info: https://docs.adyen.com/online-payments/refund
diff --git a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario5-Void the payment/Payments - Cancel/event.test.js b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario5-Void the payment/Payments - Cancel/event.test.js
index dcf3f191643..cfbd9695bd1 100644
--- a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario5-Void the payment/Payments - Cancel/event.test.js
+++ b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario5-Void the payment/Payments - Cancel/event.test.js
@@ -22,7 +22,7 @@ pm.test("[POST]::/payments/:id/cancel - Response has JSON Body", function () {
let jsonData = {};
try {
jsonData = pm.response.json();
-} catch (e) {}
+} catch (e) { }
// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id
if (jsonData?.payment_id) {
@@ -53,9 +53,9 @@ if (jsonData?.client_secret) {
// Response body should have value "cancelled" for "status"
if (jsonData?.status) {
pm.test(
- "[POST]::/payments/:id/cancel - Content check if value for 'status' matches 'cancelled'",
+ "[POST]::/payments/:id/cancel - Content check if value for 'status' matches 'processing'",
function () {
- pm.expect(jsonData.status).to.eql("cancelled");
+ pm.expect(jsonData.status).to.eql("processing");
},
);
}
diff --git a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario5-Void the payment/Payments - Retrieve/event.test.js b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario5-Void the payment/Payments - Retrieve/event.test.js
index 5e52e13a59e..ec02aad8626 100644
--- a/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario5-Void the payment/Payments - Retrieve/event.test.js
+++ b/postman/collection-dir/adyen_uk/Flow Testcases/Happy Cases/Scenario5-Void the payment/Payments - Retrieve/event.test.js
@@ -19,7 +19,7 @@ pm.test("[GET]::/payments/:id - Response has JSON Body", function () {
let jsonData = {};
try {
jsonData = pm.response.json();
-} catch (e) {}
+} catch (e) { }
// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id
if (jsonData?.payment_id) {
@@ -63,9 +63,9 @@ if (jsonData?.client_secret) {
// Response body should have value "cancelled" for "status"
if (jsonData?.status) {
pm.test(
- "[POST]::/payments/:id - Content check if value for 'status' matches 'cancelled'",
+ "[POST]::/payments/:id - Content check if value for 'status' matches 'processing'",
function () {
- pm.expect(jsonData.status).to.eql("cancelled");
+ pm.expect(jsonData.status).to.eql("processing");
},
);
}
diff --git a/postman/collection-dir/adyen_uk/Flow Testcases/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/adyen_uk/Flow Testcases/QuickStart/Payment Connector - Create/request.json
index b5002aeca8e..401201dff64 100644
--- a/postman/collection-dir/adyen_uk/Flow Testcases/QuickStart/Payment Connector - Create/request.json
+++ b/postman/collection-dir/adyen_uk/Flow Testcases/QuickStart/Payment Connector - Create/request.json
@@ -46,7 +46,7 @@
"key1": "{{connector_key1}}",
"api_secret": "{{connector_api_secret}}"
},
- "test_mode": false,
+ "test_mode": true,
"disabled": false,
"business_country": "US",
"business_label": "default",
@@ -56,12 +56,17 @@
"payment_method_types": [
{
"payment_method_type": "credit",
- "card_networks": ["AmericanExpress",
- "Discover",
- "Interac",
- "JCB",
- "Mastercard",
- "Visa", "DinersClub","UnionPay","RuPay"],
+ "card_networks": [
+ "AmericanExpress",
+ "Discover",
+ "Interac",
+ "JCB",
+ "Mastercard",
+ "Visa",
+ "DinersClub",
+ "UnionPay",
+ "RuPay"
+ ],
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
@@ -69,12 +74,17 @@
},
{
"payment_method_type": "debit",
- "card_networks": ["AmericanExpress",
- "Discover",
- "Interac",
- "JCB",
- "Mastercard",
- "Visa", "DinersClub","UnionPay","RuPay"],
+ "card_networks": [
+ "AmericanExpress",
+ "Discover",
+ "Interac",
+ "JCB",
+ "Mastercard",
+ "Visa",
+ "DinersClub",
+ "UnionPay",
+ "RuPay"
+ ],
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
@@ -203,15 +213,15 @@
{
"payment_method": "gift_card",
"payment_method_types": [
- {
- "payment_method_type": "givex",
- "minimum_amount": 1,
- "maximum_amount": 68607706,
- "recurring_enabled": true,
- "installment_payment_enabled": true
- }
+ {
+ "payment_method_type": "givex",
+ "minimum_amount": 1,
+ "maximum_amount": 68607706,
+ "recurring_enabled": true,
+ "installment_payment_enabled": true
+ }
]
- },
+ },
{
"payment_method": "bank_redirect",
"payment_method_types": [
@@ -303,7 +313,10 @@
{
"type": "CARD",
"parameters": {
- "allowed_auth_methods": ["PAN_ONLY", "CRYPTOGRAM_3DS"],
+ "allowed_auth_methods": [
+ "PAN_ONLY",
+ "CRYPTOGRAM_3DS"
+ ],
"allowed_card_networks": [
"AMEX",
"DISCOVER",
@@ -327,8 +340,14 @@
},
"url": {
"raw": "{{baseUrl}}/account/:account_id/connectors",
- "host": ["{{baseUrl}}"],
- "path": ["account", ":account_id", "connectors"],
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "account",
+ ":account_id",
+ "connectors"
+ ],
"variable": [
{
"key": "account_id",
@@ -338,4 +357,4 @@
]
},
"description": "Create a new Payment Connector for the merchant account. The connector could be a payment processor / facilitator / acquirer or specialised services like Fraud / Accounting etc."
-}
+}
\ No newline at end of file
|
2024-03-01T10:37:16Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [X] Bugfix
- [ ] New feature
- [X] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
- Update Connector Account configs for WASM build
- Update Postman Collection test case for Cancelled payments
- Make `endpoint_prefix` as Optional in MCA-create
- Change `connector_refund_id` to `psp_reference`
- Add support to enforce 3DS
### 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).
-->
#3911
## 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 manual capture payment and Cancel it, it should go into processing
```
curl --location 'http://localhost:8080/payments/pay_7RzGoWYbCpeSHynBpytc/cancel' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_LyWBxSXvkIRgcdWNLamgVQul9tMWq2axdKYlmJSwSFbv0nfDsppaJ6UwSbny0PBm' \
--data '{"cancellation_reason":"requested_by_customer"}'
```
RESPONSE:
```
{
"payment_id": "pay_AF6YTcabCeegWRQUWjdZ",
"merchant_id": "postman_merchant_GHAction_b6d214c4-4173-4a86-b4e1-52478efba2ca",
"status": "processing",
"amount": 2134,
"net_amount": 2134,
"amount_capturable": 0,
"amount_received": null,
"connector": "adyen",
"client_secret": "pay_AF6YTcabCeegWRQUWjdZ_secret_fkz68YL0UTuAJ64Tlji8",
"created": "2024-03-01T08:35:04.606Z",
"currency": "USD",
"customer_id": "StripeCustomer",
"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": "manual",
"payment_method": "card",
"payment_method_data": {
"card": {
"last4": "8431",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "371449",
"card_extended_bin": "37144963",
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": "joseph Doe"
}
},
"payment_token": null,
"shipping": {
"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": null,
"country_code": null
},
"email": null
},
"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": null,
"country_code": null
},
"email": null
},
"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": "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": "H2GSJ9JB3RJWHST5",
"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_AF6YTcabCeegWRQUWjdZ_1",
"payment_link": null,
"profile_id": "pro_KNzwSZXU8MXNySCtfhtI",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_kwbRKJxDNAJaEtZkdVFF",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"expires_on": "2024-03-01T08:50:04.606Z",
"fingerprint": null
}
```
- For Refunds Check the `connector_refund_id` and match with Connector psp_reference
- Test 3DS payments with normal card and `auth_type` as `three_ds`, 3DS should be triggered
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_5dUdESXJ81peNfBZoKwB47YehzdbXBzraGgh69wH0ZtFad9hHHT3isDg7ymJiHZc' \
--data-raw '{
"amount": 2121,
"currency": "CZK",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"amount_to_capture": 2121,
"customer_id": "StripeCustomer",
"email": "guest@example.com",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+1",
"description": "Its my first payment request",
"authentication_type": "three_ds",
"return_url": "https://duck.com",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "371449635398431",
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": "joseph Doe",
"card_cvc": "7373"
}
},
"routing": {
"type": "single",
"data": "adyen"
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "PiX"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "PiX"
}
},
"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": "125.0.0.1"
},
"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_BgVVHyaRkDKAoQJVDNPR",
"merchant_id": "postman_merchant_GHAction_9bd45c1b-7ecb-4ef6-b359-2e0dc1e68085",
"status": "requires_customer_action",
"amount": 2121,
"net_amount": 2121,
"amount_capturable": 2121,
"amount_received": null,
"connector": "adyen",
"client_secret": "pay_BgVVHyaRkDKAoQJVDNPR_secret_mQHYTu9kWz1eluaPRbIc",
"created": "2024-03-01T10:59:44.255Z",
"currency": "CZK",
"customer_id": "StripeCustomer",
"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": "8431",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "371449",
"card_extended_bin": "37144963",
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": "joseph Doe"
}
},
"payment_token": null,
"shipping": {
"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": null,
"country_code": null
},
"email": null
},
"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": null,
"country_code": null
},
"email": null
},
"order_details": null,
"email": "guest@example.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_BgVVHyaRkDKAoQJVDNPR/postman_merchant_GHAction_9bd45c1b-7ecb-4ef6-b359-2e0dc1e68085/pay_BgVVHyaRkDKAoQJVDNPR_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": {
"customer_id": "StripeCustomer",
"created_at": 1709290784,
"expires": 1709294384,
"secret": "epk_4ae0f11719b54f94a2170e2ec4fec826"
},
"manual_retry_allowed": null,
"connector_transaction_id": "P27VSB5K9MBX8N82",
"frm_message": null,
"metadata": {
"udf1": "value1",
"login_date": "2019-09-10T10:11:12Z",
"new_customer": "true"
},
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "P27VSB5K9MBX8N82",
"payment_link": null,
"profile_id": "pro_9rma6ktlyR6eBcN16AW3",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_pXK3IcyuTlLvrUVdT9sC",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"expires_on": "2024-03-01T11:14:44.255Z",
"fingerprint": 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
f95beaa189f17a6e117971a749e2b4595e1e2fc3
|
|
juspay/hyperswitch
|
juspay__hyperswitch-3903
|
Bug: [BUG] : [Adyen] No configuration for production endpoint
### Bug Description
There is no configuration for production endpoint, currently only sbx url is added in config files, also there is no provision to input `prefix` provided by Adyen to be added in each url for all the merchants
### Expected Behavior
Configure production url and provision to support appending unique prefix provided by Adyen to each merchant
### Actual Behavior
There is no configuration for production endpoint, currently only sbx url is added in config files, also there is no provision to input `prefix` provided by Adyen to be added in each url for all the merchants
### 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/config/config.example.toml b/config/config.example.toml
index abe3f6b4e08..760cc2bdd00 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -409,6 +409,10 @@ afterpay_clearpay = { fields = { stripe = [ # payment_method_type = afterpay_cle
payout_eligibility = true # Defaults the eligibility of a payout method to true in case connector does not provide checks for payout eligibility
[pm_filters.adyen]
+sofort = { country = "AT,BE,DE,ES,CH,NL", currency = "CHF,EUR"}
+paypal = { country = "AU,NZ,CN,JP,HK,MY,TH,KR,PH,ID,AE,KW,BR,ES,GB,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,FI,RO,HR,UA,MT,SI,GI,PT,IE,CZ,EE,LT,LV,IT,PL,IS,CA,US", currency = "AUD,BRL,CAD,CZK,DKK,EUR,HKD,HUF,INR,JPY,MYR,MXN,NZD,NOK,PHP,PLN,RUB,GBP,SGD,SEK,CHF,THB,USD" }
+klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NO,PL,PT,RO,ES,SE,CH,NL,GB,US", currency = "AUD,EUR,CAD,CZK,DKK,NOK,PLN,RON,SEK,CHF,GBP,USD"}
+ideal = { country = "NL", currency = "EUR" }
online_banking_fpx = { country = "MY", currency = "MYR" }
online_banking_thailand = { country = "TH", currency = "THB" }
touch_n_go = { country = "MY", currency = "MYR" }
diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml
index dba591ae679..dd755c9dd22 100644
--- a/config/deployments/integration_test.toml
+++ b/config/deployments/integration_test.toml
@@ -1,7 +1,7 @@
[bank_config]
eps.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"
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"
-ideal.adyen.banks = "abn_amro,asn_bank,bunq,handelsbanken,ing,knab,moneyou,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot"
+ideal.adyen.banks = "abn_amro,asn_bank,bunq,ing,knab,n26,nationale_nederlanden,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot,yoursafe"
ideal.stripe.banks = "abn_amro,asn_bank,bunq,handelsbanken,ing,knab,moneyou,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot"
online_banking_czech_republic.adyen.banks = "ceska_sporitelna,komercni_banka,platnosc_online_karta_platnicza"
online_banking_fpx.adyen.banks = "affin_bank,agro_bank,alliance_bank,am_bank,bank_islam,bank_muamalat,bank_rakyat,bank_simpanan_nasional,cimb_bank,hong_leong_bank,hsbc_bank,kuwait_finance_house,maybank,ocbc_bank,public_bank,rhb_bank,standard_chartered_bank,uob_bank"
@@ -174,7 +174,7 @@ google_pay = { country = "AU,NZ,JP,HK,SG,MY,TH,VN,BH,AE,KW,BR,ES,GB,SE,NO,SK,AT,
ideal = { country = "NL", currency = "EUR" }
indomaret = { country = "ID", currency = "IDR" }
kakao_pay = { country = "KR", currency = "KRW" }
-klarna = { country = "AT,ES,GB,SE,NO,AT,NL,DE,CH,BE,FR,DK,FI,PT,IE,IT,PL,CA,US", currency = "USD,GBP,EUR,CHF,DKK,SEK,NOK,AUD,PLN,CAD" }
+klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NO,PL,PT,RO,ES,SE,CH,NL,GB,US", currency = "AUD,EUR,CAD,CZK,DKK,NOK,PLN,RON,SEK,CHF,GBP,USD"}
lawson = { country = "JP", currency = "JPY" }
mandiri_va = { country = "ID", currency = "IDR" }
mb_way = { country = "PT", currency = "EUR" }
@@ -193,12 +193,13 @@ oxxo = { country = "MX", currency = "MXN" }
pay_bright = { country = "CA", currency = "CAD" }
pay_easy = { country = "JP", currency = "JPY" }
pay_safe_card = { country = "AT,AU,BE,BR,BE,CA,HR,CY,CZ,DK,FI,FR,GE,DE,GI,HU,IS,IE,KW,LV,IE,LI,LT,LU,MT,MX,MD,ME,NL,NZ,NO,PY,PE,PL,PT,RO,SA,RS,SK,SI,ES,SE,CH,TR,AE,GB,US,UY", currency = "EUR,AUD,BRL,CAD,CZK,DKK,GEL,GIP,HUF,KWD,CHF,MXN,MDL,NZD,NOK,PYG,PEN,PLN,RON,SAR,RSD,SEK,TRY,AED,GBP,USD,UYU" }
-paypal = { country = "AU,NZ,CN,JP,HK,MY,TH,KR,PH,ID,AE,KW,BR,ES,GB,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,FI,RO,HR,UA,MT,SI,GI,PT,IE,CZ,EE,LT,LV,IT,PL,IS,CA,US", currency = "AUD,BRL,CAD,CZK,DKK,EUR,HKD,HUF,INR,JPY,MYR,MXN,NZD,NOK,PHP,PLN,RUB,GBP,SGD,SEK,CHF,THB,USD" }
permata_bank_transfer = { country = "ID", currency = "IDR" }
seicomart = { country = "JP", currency = "JPY" }
sepa = { country = "ES,SK,AT,NL,DE,BE,FR,FI,PT,IE,EE,LT,LV,IT", currency = "EUR" }
seven_eleven = { country = "JP", currency = "JPY" }
-sofort = { country = "ES,GB,SE,AT,NL,DE,CH,BE,FR,FI,IT,PL", currency = "EUR" }
+sofort = { country = "AT,BE,DE,ES,CH,NL", currency = "CHF,EUR"}
+paypal = { country = "AU,NZ,CN,JP,HK,MY,TH,KR,PH,ID,AE,KW,BR,ES,GB,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,FI,RO,HR,UA,MT,SI,GI,PT,IE,CZ,EE,LT,LV,IT,PL,IS,CA,US", currency = "AUD,BRL,CAD,CZK,DKK,EUR,HKD,HUF,INR,JPY,MYR,MXN,NZD,NOK,PHP,PLN,RUB,GBP,SGD,SEK,CHF,THB,USD" }
+
swish = { country = "SE", currency = "SEK" }
touch_n_go = { country = "MY", currency = "MYR" }
trustly = { country = "ES,GB,SE,NO,AT,NL,DE,DK,FI,EE,LT,LV", currency = "CZK,DKK,EUR,GBP,NOK,SEK" }
diff --git a/config/deployments/production.toml b/config/deployments/production.toml
index 48bb9d33e3f..9c2f25b24ff 100644
--- a/config/deployments/production.toml
+++ b/config/deployments/production.toml
@@ -1,7 +1,7 @@
[bank_config]
eps.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"
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"
-ideal.adyen.banks = "abn_amro,asn_bank,bunq,handelsbanken,ing,knab,moneyou,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot"
+ideal.adyen.banks = "abn_amro,asn_bank,bunq,ing,knab,n26,nationale_nederlanden,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot,yoursafe"
ideal.stripe.banks = "abn_amro,asn_bank,bunq,handelsbanken,ing,knab,moneyou,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot"
online_banking_czech_republic.adyen.banks = "ceska_sporitelna,komercni_banka,platnosc_online_karta_platnicza"
online_banking_fpx.adyen.banks = "affin_bank,agro_bank,alliance_bank,am_bank,bank_islam,bank_muamalat,bank_rakyat,bank_simpanan_nasional,cimb_bank,hong_leong_bank,hsbc_bank,kuwait_finance_house,maybank,ocbc_bank,public_bank,rhb_bank,standard_chartered_bank,uob_bank"
@@ -17,8 +17,8 @@ payout_connector_list = "wise"
[connectors]
aci.base_url = "https://eu-test.oppwa.com/"
-adyen.base_url = "https://checkout-test.adyen.com/"
-adyen.secondary_base_url = "https://pal-test.adyen.com/"
+adyen.base_url = "https://{{merchant_endpoint_prefix}}-checkout-live.adyenpayments.com/"
+adyen.secondary_base_url = "https://{{merchant_endpoint_prefix}}-pal-live.adyenpayments.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"
@@ -189,7 +189,7 @@ google_pay = { country = "AE,AG,AL,AO,AR,AS,AT,AU,AZ,BE,BG,BH,BR,BY,CA,CH,CL,CO,
ideal = { country = "NL", currency = "EUR" }
indomaret = { country = "ID", currency = "IDR" }
kakao_pay = { country = "KR", currency = "KRW" }
-klarna = { country = "AT,BE,CA,CH,DE,DK,ES,FI,FR,GB,IE,IT,NL,NO,PL,PT,SE,GB,US", currency = "AUD,CAD,CHF,DKK,EUR,GBP,NOK,PLN,SEK,USD" }
+klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NO,PL,PT,RO,ES,SE,CH,NL,GB,US", currency = "AUD,EUR,CAD,CZK,DKK,NOK,PLN,RON,SEK,CHF,GBP,USD"}
lawson = { country = "JP", currency = "JPY" }
mandiri_va = { country = "ID", currency = "IDR" }
mb_way = { country = "PT", currency = "EUR" }
@@ -213,7 +213,7 @@ permata_bank_transfer = { country = "ID", currency = "IDR" }
seicomart = { country = "JP", currency = "JPY" }
sepa = { country = "ES,SK,AT,NL,DE,BE,FR,FI,PT,IE,EE,LT,LV,IT", currency = "EUR" }
seven_eleven = { country = "JP", currency = "JPY" }
-sofort = { country = "AT,BE,CH,DE,ES,FI,FR,GB,IT,NL,PL,SE,GB", currency = "EUR" }
+sofort = { country = "AT,BE,DE,ES,CH,NL", currency = "CHF,EUR"}
swish = { country = "SE", currency = "SEK" }
touch_n_go = { country = "MY", currency = "MYR" }
trustly = { country = "ES,GB,SE,NO,AT,NL,DE,DK,FI,EE,LT,LV", currency = "CZK,DKK,EUR,GBP,NOK,SEK" }
diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml
index 8723f871c34..5c052e5c85f 100644
--- a/config/deployments/sandbox.toml
+++ b/config/deployments/sandbox.toml
@@ -1,7 +1,7 @@
[bank_config]
eps.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"
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"
-ideal.adyen.banks = "abn_amro,asn_bank,bunq,handelsbanken,ing,knab,moneyou,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot"
+ideal.adyen.banks = "abn_amro,asn_bank,bunq,ing,knab,n26,nationale_nederlanden,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot,yoursafe"
ideal.stripe.banks = "abn_amro,asn_bank,bunq,handelsbanken,ing,knab,moneyou,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot"
online_banking_czech_republic.adyen.banks = "ceska_sporitelna,komercni_banka,platnosc_online_karta_platnicza"
online_banking_fpx.adyen.banks = "affin_bank,agro_bank,alliance_bank,am_bank,bank_islam,bank_muamalat,bank_rakyat,bank_simpanan_nasional,cimb_bank,hong_leong_bank,hsbc_bank,kuwait_finance_house,maybank,ocbc_bank,public_bank,rhb_bank,standard_chartered_bank,uob_bank"
@@ -189,7 +189,7 @@ google_pay = { country = "AU,NZ,JP,HK,SG,MY,TH,VN,BH,AE,KW,BR,ES,GB,SE,NO,SK,AT,
ideal = { country = "NL", currency = "EUR" }
indomaret = { country = "ID", currency = "IDR" }
kakao_pay = { country = "KR", currency = "KRW" }
-klarna = { country = "AT,ES,GB,SE,NO,AT,NL,DE,CH,BE,FR,DK,FI,PT,IE,IT,PL,CA,US", currency = "USD,GBP,EUR,CHF,DKK,SEK,NOK,AUD,PLN,CAD" }
+klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NO,PL,PT,RO,ES,SE,CH,NL,GB,US", currency = "AUD,EUR,CAD,CZK,DKK,NOK,PLN,RON,SEK,CHF,GBP,USD"}
lawson = { country = "JP", currency = "JPY" }
mandiri_va = { country = "ID", currency = "IDR" }
mb_way = { country = "PT", currency = "EUR" }
@@ -213,7 +213,7 @@ permata_bank_transfer = { country = "ID", currency = "IDR" }
seicomart = { country = "JP", currency = "JPY" }
sepa = { country = "ES,SK,AT,NL,DE,BE,FR,FI,PT,IE,EE,LT,LV,IT", currency = "EUR" }
seven_eleven = { country = "JP", currency = "JPY" }
-sofort = { country = "ES,GB,SE,AT,NL,DE,CH,BE,FR,FI,IT,PL", currency = "EUR" }
+sofort = { country = "AT,BE,DE,ES,CH,NL", currency = "CHF,EUR"}
swish = { country = "SE", currency = "SEK" }
touch_n_go = { country = "MY", currency = "MYR" }
trustly = { country = "ES,GB,SE,NO,AT,NL,DE,DK,FI,EE,LT,LV", currency = "CZK,DKK,EUR,GBP,NOK,SEK" }
diff --git a/config/development.toml b/config/development.toml
index d69719bd419..824ceaa8eb6 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -256,7 +256,7 @@ adyen = { banks = "bank_austria,bawag_psk_ag,dolomitenbank,easybank_ag,erste_ban
[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" }
+adyen = { banks = "abn_amro,asn_bank,bunq,ing,knab,n26,nationale_nederlanden,rabobank,regiobank,revolut,sns_bank,triodos_bank,van_lanschot, yoursafe" }
[bank_config.online_banking_czech_republic]
adyen = { banks = "ceska_sporitelna,komercni_banka,platnosc_online_karta_platnicza" }
@@ -314,14 +314,14 @@ mobile_pay = { country = "DK,FI", currency = "DKK,SEK,NOK,EUR" }
ali_pay = { country = "AU,JP,HK,SG,MY,TH,ES,GB,SE,NO,AT,NL,DE,CY,CH,BE,FR,DK,FI,RO,MT,SI,GR,PT,IE,IT,CA,US", currency = "USD,EUR,GBP,JPY,AUD,SGD,CHF,SEK,NOK,NZD,THB,HKD,CAD" }
we_chat_pay = { country = "AU,NZ,CN,JP,HK,SG,ES,GB,SE,NO,AT,NL,DE,CY,CH,BE,FR,DK,LI,MT,SI,GR,PT,IT,CA,US", currency = "AUD,CAD,CNY,EUR,GBP,HKD,JPY,NZD,SGD,USD" }
mb_way = { country = "PT", currency = "EUR" }
-klarna = { country = "AT,ES,GB,SE,NO,AT,NL,DE,CH,BE,FR,DK,FI,PT,IE,IT,PL,CA,US", currency = "USD,GBP,EUR,CHF,DKK,SEK,NOK,AUD,PLN,CAD" }
+klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NO,PL,PT,RO,ES,SE,CH,NL,GB,US", currency = "AUD,EUR,CAD,CZK,DKK,NOK,PLN,RON,SEK,CHF,GBP,USD"}
affirm = { country = "US", currency = "USD" }
afterpay_clearpay = { country = "AU,NZ,ES,GB,FR,IT,CA,US", currency = "GBP" }
pay_bright = { country = "CA", currency = "CAD" }
walley = { country = "SE,NO,DK,FI", currency = "DKK,EUR,NOK,SEK" }
giropay = { country = "DE", currency = "EUR" }
eps = { country = "AT", currency = "EUR" }
-sofort = { country = "ES,GB,SE,AT,NL,DE,CH,BE,FR,FI,IT,PL", currency = "EUR" }
+sofort = { country = "AT,BE,DE,ES,CH,NL", currency = "CHF,EUR"}
ideal = { country = "NL", currency = "EUR" }
blik = {country = "PL", currency = "PLN"}
trustly = {country = "ES,GB,SE,NO,AT,NL,DE,DK,FI,EE,LT,LV", currency = "CZK,DKK,EUR,GBP,NOK,SEK"}
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index 8170132bb85..0aaeefb7ae8 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -305,6 +305,11 @@ family_mart = {country = "JP", currency = "JPY"}
seicomart = {country = "JP", currency = "JPY"}
pay_easy = {country = "JP", currency = "JPY"}
boleto = { country = "BR", currency = "BRL" }
+ideal = { country = "NL", currency = "EUR" }
+klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NO,PL,PT,RO,ES,SE,CH,NL,GB,US", currency = "AUD,EUR,CAD,CZK,DKK,NOK,PLN,RON,SEK,CHF,GBP,USD"}
+paypal = { country = "AU,NZ,CN,JP,HK,MY,TH,KR,PH,ID,AE,KW,BR,ES,GB,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,FI,RO,HR,UA,MT,SI,GI,PT,IE,CZ,EE,LT,LV,IT,PL,IS,CA,US", currency = "AUD,BRL,CAD,CZK,DKK,EUR,HKD,HUF,INR,JPY,MYR,MXN,NZD,NOK,PHP,PLN,RUB,GBP,SGD,SEK,CHF,THB,USD" }
+sofort = { country = "AT,BE,DE,ES,CH,NL", currency = "CHF,EUR"}
+
[pm_filters.volt]
open_banking_uk = {country = "DE,GB,AT,BE,CY,EE,ES,FI,FR,GR,HR,IE,IT,LT,LU,LV,MT,NL,PT,SI,SK,BG,CZ,DK,HU,NO,PL,RO,SE,AU,BR", currency = "EUR,GBP,DKK,NOK,PLN,SEK,AUD,BRL"}
diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs
index 45851e4c11b..60c48f3d03c 100644
--- a/crates/api_models/src/enums.rs
+++ b/crates/api_models/src/enums.rs
@@ -434,6 +434,9 @@ pub enum BankNames {
TsbBank,
TescoBank,
UlsterBank,
+ Yoursafe,
+ N26,
+ NationaleNederlanden,
}
#[derive(
diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml
index 693ea69ff4e..e1f731c25e4 100644
--- a/crates/connector_configs/toml/development.toml
+++ b/crates/connector_configs/toml/development.toml
@@ -232,6 +232,8 @@ api_key="Adyen API Key"
key1="Adyen Account Id"
[adyen.connector_webhook_details]
merchant_secret="Source verification key"
+[adyen.metadata]
+endpoint_prefix="Live endpoint prefix"
[adyen.metadata.google_pay]
merchant_name="Google Pay Merchant Name"
gateway_merchant_id="Google Pay Merchant Key"
@@ -2506,6 +2508,8 @@ api_key="Api Key"
payment_method_type = "sepa"
[[adyen_payout.wallet]]
payment_method_type = "paypal"
+[adyen_payout.metadata]
+ endpoint_prefix="Live endpoint prefix"
[adyen_payout.connector_auth.SignatureKey]
api_key = "Adyen API Key (Payout creation)"
api_secret = "Adyen Key (Payout submission)"
diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml
index 78f6f8d2a76..a463d546ffb 100644
--- a/crates/connector_configs/toml/production.toml
+++ b/crates/connector_configs/toml/production.toml
@@ -124,6 +124,9 @@ key1="Adyen Account Id"
[adyen.connector_webhook_details]
merchant_secret="Source verification key"
+[adyen.metadata]
+endpoint_prefix="Live endpoint prefix"
+
[adyen.metadata.google_pay]
merchant_name="Google Pay Merchant Name"
gateway_merchant_id="Google Pay Merchant Key"
diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml
index dbb6284fbe9..cf94e1d6222 100644
--- a/crates/connector_configs/toml/sandbox.toml
+++ b/crates/connector_configs/toml/sandbox.toml
@@ -232,6 +232,8 @@ api_key="Adyen API Key"
key1="Adyen Account Id"
[adyen.connector_webhook_details]
merchant_secret="Source verification key"
+[adyen.metadata]
+endpoint_prefix="Live endpoint prefix"
[adyen.metadata.google_pay]
merchant_name="Google Pay Merchant Name"
gateway_merchant_id="Google Pay Merchant Key"
@@ -2508,6 +2510,8 @@ api_key="Api Key"
payment_method_type = "sepa"
[[adyen_payout.wallet]]
payment_method_type = "paypal"
+[adyen_payout.metadata]
+ endpoint_prefix="Live endpoint prefix"
[adyen_payout.connector_auth.SignatureKey]
api_key = "Adyen API Key (Payout creation)"
api_secret = "Adyen Key (Payout submission)"
diff --git a/crates/router/src/connector/adyen.rs b/crates/router/src/connector/adyen.rs
index 771ad993ac9..261495e2bfa 100644
--- a/crates/router/src/connector/adyen.rs
+++ b/crates/router/src/connector/adyen.rs
@@ -33,6 +33,8 @@ use crate::{
utils::{crypto, ByteSliceExt, BytesExt, OptionExt},
};
+const ADYEN_API_VERSION: &str = "v68";
+
#[derive(Debug, Clone)]
pub struct Adyen;
@@ -268,6 +270,23 @@ impl
// Not Implemented (R)
}
+fn build_env_specific_endpoint(
+ base_url: &str,
+ test_mode: Option<bool>,
+ connector_metadata: &Option<common_utils::pii::SecretSerdeValue>,
+) -> CustomResult<String, errors::ConnectorError> {
+ if test_mode.unwrap_or(true) {
+ Ok(base_url.to_string())
+ } else {
+ let adyen_connector_metadata_object =
+ transformers::AdyenConnectorMetadataObject::try_from(connector_metadata)?;
+ Ok(base_url.replace(
+ "{{merchant_endpoint_prefix}}",
+ &adyen_connector_metadata_object.endpoint_prefix,
+ ))
+ }
+}
+
impl
services::ConnectorIntegration<
api::SetupMandate,
@@ -293,10 +312,15 @@ impl
fn get_url(
&self,
- _req: &types::SetupMandateRouterData,
+ req: &types::SetupMandateRouterData,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- Ok(format!("{}{}", self.base_url(connectors), "v68/payments"))
+ let endpoint = build_env_specific_endpoint(
+ self.base_url(connectors),
+ req.test_mode,
+ &req.connector_meta_data,
+ )?;
+ Ok(format!("{}{}/payments", endpoint, ADYEN_API_VERSION))
}
fn get_request_body(
&self,
@@ -418,11 +442,15 @@ impl
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let id = req.request.connector_transaction_id.as_str();
- Ok(format!(
- "{}{}/{}/captures",
+
+ let endpoint = build_env_specific_endpoint(
self.base_url(connectors),
- "v68/payments",
- id
+ req.test_mode,
+ &req.connector_meta_data,
+ )?;
+ Ok(format!(
+ "{}{}/payments/{}/captures",
+ endpoint, ADYEN_API_VERSION, id
))
}
fn get_request_body(
@@ -560,13 +588,17 @@ impl
fn get_url(
&self,
- _req: &types::RouterData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>,
+ req: &types::RouterData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- Ok(format!(
- "{}{}",
+ let endpoint = build_env_specific_endpoint(
self.base_url(connectors),
- "v68/payments/details"
+ req.test_mode,
+ &req.connector_meta_data,
+ )?;
+ Ok(format!(
+ "{}{}/payments/details",
+ endpoint, ADYEN_API_VERSION
))
}
@@ -681,10 +713,15 @@ impl
fn get_url(
&self,
- _req: &types::PaymentsAuthorizeRouterData,
+ req: &types::PaymentsAuthorizeRouterData,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- Ok(format!("{}{}", self.base_url(connectors), "v68/payments"))
+ let endpoint = build_env_specific_endpoint(
+ self.base_url(connectors),
+ req.test_mode,
+ &req.connector_meta_data,
+ )?;
+ Ok(format!("{}{}/payments", endpoint, ADYEN_API_VERSION))
}
fn get_request_body(
@@ -785,12 +822,17 @@ impl
fn get_url(
&self,
- _req: &types::PaymentsPreProcessingRouterData,
+ req: &types::PaymentsPreProcessingRouterData,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
+ let endpoint = build_env_specific_endpoint(
+ self.base_url(connectors),
+ req.test_mode,
+ &req.connector_meta_data,
+ )?;
Ok(format!(
- "{}v69/paymentMethods/balance",
- self.base_url(connectors)
+ "{}{}/paymentMethods/balance",
+ endpoint, ADYEN_API_VERSION
))
}
@@ -911,11 +953,16 @@ impl
req: &types::PaymentsCancelRouterData,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- let id = req.request.connector_transaction_id.as_str();
- Ok(format!(
- "{}v68/payments/{}/cancels",
+ let id = req.request.connector_transaction_id.clone();
+
+ let endpoint = build_env_specific_endpoint(
self.base_url(connectors),
- id
+ req.test_mode,
+ &req.connector_meta_data,
+ )?;
+ Ok(format!(
+ "{}{}/payments/{}/cancels",
+ endpoint, ADYEN_API_VERSION, id
))
}
@@ -991,12 +1038,17 @@ impl services::ConnectorIntegration<api::PoCancel, types::PayoutsData, types::Pa
{
fn get_url(
&self,
- _req: &types::PayoutsRouterData<api::PoCancel>,
+ req: &types::PayoutsRouterData<api::PoCancel>,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
+ let endpoint = build_env_specific_endpoint(
+ connectors.adyen.secondary_base_url.as_str(),
+ req.test_mode,
+ &req.connector_meta_data,
+ )?;
Ok(format!(
- "{}pal/servlet/Payout/v68/declineThirdParty",
- connectors.adyen.secondary_base_url
+ "{}pal/servlet/Payout/{}/declineThirdParty",
+ endpoint, ADYEN_API_VERSION
))
}
@@ -1083,12 +1135,17 @@ impl services::ConnectorIntegration<api::PoCreate, types::PayoutsData, types::Pa
{
fn get_url(
&self,
- _req: &types::PayoutsRouterData<api::PoCreate>,
+ req: &types::PayoutsRouterData<api::PoCreate>,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
+ let endpoint = build_env_specific_endpoint(
+ connectors.adyen.secondary_base_url.as_str(),
+ req.test_mode,
+ &req.connector_meta_data,
+ )?;
Ok(format!(
- "{}pal/servlet/Payout/v68/storeDetailAndSubmitThirdParty",
- connectors.adyen.secondary_base_url
+ "{}pal/servlet/Payout/{}/storeDetailAndSubmitThirdParty",
+ endpoint, ADYEN_API_VERSION
))
}
@@ -1180,10 +1237,15 @@ impl
{
fn get_url(
&self,
- _req: &types::PayoutsRouterData<api::PoEligibility>,
+ req: &types::PayoutsRouterData<api::PoEligibility>,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- Ok(format!("{}v68/payments", self.base_url(connectors),))
+ let endpoint = build_env_specific_endpoint(
+ self.base_url(connectors),
+ req.test_mode,
+ &req.connector_meta_data,
+ )?;
+ Ok(format!("{}{}/payments", endpoint, ADYEN_API_VERSION))
}
fn get_headers(
@@ -1277,9 +1339,15 @@ impl services::ConnectorIntegration<api::PoFulfill, types::PayoutsData, types::P
req: &types::PayoutsRouterData<api::PoFulfill>,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
+ let endpoint = build_env_specific_endpoint(
+ connectors.adyen.secondary_base_url.as_str(),
+ req.test_mode,
+ &req.connector_meta_data,
+ )?;
Ok(format!(
- "{}pal/servlet/Payout/v68/{}",
- connectors.adyen.secondary_base_url,
+ "{}pal/servlet/Payout/{}/{}",
+ endpoint,
+ ADYEN_API_VERSION,
match req.request.payout_type {
storage_enums::PayoutType::Bank | storage_enums::PayoutType::Wallet =>
"confirmThirdParty".to_string(),
@@ -1407,10 +1475,15 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = req.request.connector_transaction_id.clone();
- Ok(format!(
- "{}v68/payments/{}/refunds",
+
+ let endpoint = build_env_specific_endpoint(
self.base_url(connectors),
- connector_payment_id
+ req.test_mode,
+ &req.connector_meta_data,
+ )?;
+ Ok(format!(
+ "{}{}/payments/{}/refunds",
+ endpoint, ADYEN_API_VERSION, connector_payment_id
))
}
@@ -1483,6 +1556,17 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref
impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData>
for Adyen
{
+ fn build_request(
+ &self,
+ _req: &types::RefundsRouterData<api::RSync>,
+ _connectors: &settings::Connectors,
+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ Err(errors::ConnectorError::FlowNotSupported {
+ flow: "Rsync".to_owned(),
+ connector: "Adyen".to_owned(),
+ }
+ .into())
+ }
}
fn get_webhook_object_from_body(
@@ -1591,7 +1675,7 @@ impl api::IncomingWebhook for Adyen {
let notif = get_webhook_object_from_body(request.body)
.change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
// for capture_event, original_reference field will have the authorized payment's PSP reference
- if adyen::is_capture_event(¬if.event_code) {
+ if adyen::is_capture_or_cancel_event(¬if.event_code) {
return Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
api_models::payments::PaymentIdType::ConnectorTransactionId(
notif
@@ -1630,6 +1714,7 @@ impl api::IncomingWebhook for Adyen {
.change_context(errors::ConnectorError::WebhookEventTypeNotFound)?;
Ok(IncomingWebhookEvent::foreign_from((
notif.event_code,
+ notif.success,
notif.additional_data.dispute_status,
)))
}
diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs
index a2fc7cc7ba4..7f20041e1fc 100644
--- a/crates/router/src/connector/adyen/transformers.rs
+++ b/crates/router/src/connector/adyen/transformers.rs
@@ -2,7 +2,7 @@
use api_models::payouts::PayoutMethodData;
use api_models::{enums, payments, webhooks};
use cards::CardNumber;
-use common_utils::ext_traits::Encode;
+use common_utils::{ext_traits::Encode, pii};
use error_stack::ResultExt;
use masking::{ExposeInterface, PeekInterface};
use reqwest::Url;
@@ -61,6 +61,21 @@ impl<T>
})
}
}
+#[derive(Debug, Default, Serialize, Deserialize)]
+pub struct AdyenConnectorMetadataObject {
+ pub endpoint_prefix: String,
+}
+
+impl TryFrom<&Option<pii::SecretSerdeValue>> for AdyenConnectorMetadataObject {
+ 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)
+ }
+}
// Adyen Types Definition
// Payments Request and Response Types
@@ -230,7 +245,7 @@ impl ForeignFrom<(bool, AdyenStatus, Option<common_enums::PaymentMethodType>)>
) -> Self {
match adyen_status {
AdyenStatus::AuthenticationFinished => Self::AuthenticationSuccessful,
- AdyenStatus::AuthenticationNotRequired => Self::Pending,
+ AdyenStatus::AuthenticationNotRequired | AdyenStatus::Received => Self::Pending,
AdyenStatus::Authorised => match is_manual_capture {
true => Self::Authorized,
// In case of Automatic capture Authorized is the final status of the payment
@@ -245,7 +260,6 @@ impl ForeignFrom<(bool, AdyenStatus, Option<common_enums::PaymentMethodType>)>
Some(common_enums::PaymentMethodType::Pix) => Self::AuthenticationPending,
_ => Self::Pending,
},
- AdyenStatus::Received => Self::Started,
#[cfg(feature = "payouts")]
AdyenStatus::PayoutConfirmReceived => Self::Started,
#[cfg(feature = "payouts")]
@@ -281,7 +295,6 @@ pub struct AdyenRefusal {
#[derive(Debug, Clone, Serialize, serde::Deserialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AdyenRedirection {
- #[serde(rename = "redirectResult")]
pub redirect_result: String,
#[serde(rename = "type")]
pub type_of_redirection_result: Option<String>,
@@ -432,6 +445,7 @@ pub struct Amount {
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "type")]
+#[serde(rename_all = "lowercase")]
pub enum AdyenPaymentMethod<'a> {
AdyenAffirm(Box<PmdForPaymentType>),
AdyenCard(Box<AdyenCard>),
@@ -1016,6 +1030,9 @@ impl TryFrom<&api_enums::BankNames> for OpenBankingUKIssuer {
| enums::BankNames::KrungsriBank
| enums::BankNames::KrungThaiBank
| enums::BankNames::TheSiamCommercialBank
+ | enums::BankNames::Yoursafe
+ | enums::BankNames::N26
+ | enums::BankNames::NationaleNederlanden
| enums::BankNames::KasikornBank => Err(errors::ConnectorError::NotSupported {
message: String::from("BankRedirect"),
connector: "Adyen",
@@ -1079,8 +1096,9 @@ pub struct AdyenCancelRequest {
#[derive(Default, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AdyenCancelResponse {
- psp_reference: String,
+ payment_psp_reference: String,
status: CancelStatus,
+ reference: String,
}
#[derive(Default, Debug, Deserialize, Serialize)]
@@ -1365,16 +1383,17 @@ impl<'a> TryFrom<&api_enums::BankNames> for AdyenTestBankNames<'a> {
api_models::enums::BankNames::AbnAmro => Self("1121"),
api_models::enums::BankNames::AsnBank => Self("1151"),
api_models::enums::BankNames::Bunq => Self("1152"),
- api_models::enums::BankNames::Handelsbanken => Self("1153"),
api_models::enums::BankNames::Ing => Self("1154"),
api_models::enums::BankNames::Knab => Self("1155"),
- api_models::enums::BankNames::Moneyou => Self("1156"),
+ api_models::enums::BankNames::N26 => Self("1156"),
+ api_models::enums::BankNames::NationaleNederlanden => Self("1157"),
api_models::enums::BankNames::Rabobank => Self("1157"),
api_models::enums::BankNames::Regiobank => Self("1158"),
api_models::enums::BankNames::Revolut => Self("1159"),
api_models::enums::BankNames::SnsBank => Self("1159"),
api_models::enums::BankNames::TriodosBank => Self("1159"),
api_models::enums::BankNames::VanLanschot => Self("1159"),
+ api_models::enums::BankNames::Yoursafe => Self("1159"),
api_models::enums::BankNames::BankAustria => {
Self("e6819e7a-f663-414b-92ec-cf7c82d2f4e5")
}
@@ -1419,6 +1438,34 @@ impl<'a> TryFrom<&api_enums::BankNames> for AdyenTestBankNames<'a> {
}
}
+pub struct AdyenBankNames<'a>(&'a str);
+
+impl<'a> TryFrom<&api_enums::BankNames> for AdyenBankNames<'a> {
+ type Error = Error;
+ fn try_from(bank: &api_enums::BankNames) -> Result<Self, Self::Error> {
+ Ok(match bank {
+ api_models::enums::BankNames::AbnAmro => Self("0031"),
+ api_models::enums::BankNames::AsnBank => Self("0761"),
+ api_models::enums::BankNames::Bunq => Self("0802"),
+ api_models::enums::BankNames::Ing => Self("0721"),
+ api_models::enums::BankNames::Knab => Self("0801"),
+ api_models::enums::BankNames::N26 => Self("0807"),
+ api_models::enums::BankNames::NationaleNederlanden => Self("0808"),
+ api_models::enums::BankNames::Rabobank => Self("0021"),
+ api_models::enums::BankNames::Regiobank => Self("0771"),
+ api_models::enums::BankNames::Revolut => Self("0805"),
+ api_models::enums::BankNames::SnsBank => Self("0751"),
+ api_models::enums::BankNames::TriodosBank => Self("0511"),
+ api_models::enums::BankNames::VanLanschot => Self("0161"),
+ api_models::enums::BankNames::Yoursafe => Self("0806"),
+ _ => Err(errors::ConnectorError::NotSupported {
+ message: String::from("BankRedirect"),
+ connector: "Adyen",
+ })?,
+ })
+ }
+}
+
impl TryFrom<&types::ConnectorAuthType> for AdyenAuthType {
type Error = Error;
fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
@@ -2079,10 +2126,12 @@ impl<'a> TryFrom<(&api::PayLaterData, Option<api_enums::CountryAlpha2>)>
}
}
-impl<'a> TryFrom<&api_models::payments::BankRedirectData> for AdyenPaymentMethod<'a> {
+impl<'a> TryFrom<(&api_models::payments::BankRedirectData, Option<bool>)>
+ for AdyenPaymentMethod<'a>
+{
type Error = Error;
fn try_from(
- bank_redirect_data: &api_models::payments::BankRedirectData,
+ (bank_redirect_data, test_mode): (&api_models::payments::BankRedirectData, Option<bool>),
) -> Result<Self, Self::Error> {
match bank_redirect_data {
api_models::payments::BankRedirectData::BancontactCard {
@@ -2154,19 +2203,33 @@ impl<'a> TryFrom<&api_models::payments::BankRedirectData> for AdyenPaymentMethod
payment_type: PaymentType::Giropay,
})))
}
- api_models::payments::BankRedirectData::Ideal { bank_name, .. } => Ok(
- AdyenPaymentMethod::Ideal(Box::new(BankRedirectionWithIssuer {
- payment_type: PaymentType::Ideal,
- issuer: Some(
+ api_models::payments::BankRedirectData::Ideal { bank_name, .. } => {
+ let issuer = if test_mode.unwrap_or(true) {
+ Some(
AdyenTestBankNames::try_from(&bank_name.ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "ideal.bank_name",
},
)?)?
.0,
- ),
- })),
- ),
+ )
+ } else {
+ Some(
+ AdyenBankNames::try_from(&bank_name.ok_or(
+ errors::ConnectorError::MissingRequiredField {
+ field_name: "ideal.bank_name",
+ },
+ )?)?
+ .0,
+ )
+ };
+ Ok(AdyenPaymentMethod::Ideal(Box::new(
+ BankRedirectionWithIssuer {
+ payment_type: PaymentType::Ideal,
+ issuer,
+ },
+ )))
+ }
api_models::payments::BankRedirectData::OnlineBankingCzechRepublic { issuer } => {
Ok(AdyenPaymentMethod::OnlineBankingCzechRepublic(Box::new(
OnlineBankingCzechRepublicData {
@@ -2692,7 +2755,8 @@ impl<'a>
let browser_info = get_browser_info(item.router_data)?;
let additional_data = get_additional_data(item.router_data);
let return_url = item.router_data.request.get_return_url()?;
- let payment_method = AdyenPaymentMethod::try_from(bank_redirect_data)?;
+ let payment_method =
+ AdyenPaymentMethod::try_from((bank_redirect_data, item.router_data.test_mode))?;
let (shopper_locale, country) = get_redirect_extra_details(item.router_data)?;
let line_items = Some(get_line_items(item));
@@ -2939,15 +3003,6 @@ impl TryFrom<&types::PaymentsCancelRouterData> for AdyenCancelRequest {
}
}
-impl From<CancelStatus> for storage_enums::AttemptStatus {
- fn from(status: CancelStatus) -> Self {
- match status {
- CancelStatus::Received => Self::Voided,
- CancelStatus::Processing => Self::Pending,
- }
- }
-}
-
impl TryFrom<types::PaymentsCancelResponseRouterData<AdyenCancelResponse>>
for types::PaymentsCancelRouterData
{
@@ -2956,14 +3011,16 @@ impl TryFrom<types::PaymentsCancelResponseRouterData<AdyenCancelResponse>>
item: types::PaymentsCancelResponseRouterData<AdyenCancelResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
- status: item.response.status.into(),
+ status: enums::AttemptStatus::Pending,
response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(item.response.psp_reference),
+ resource_id: types::ResponseId::ConnectorTransactionId(
+ item.response.payment_psp_reference,
+ ),
redirection_data: None,
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
- connector_response_reference_id: None,
+ connector_response_reference_id: Some(item.response.reference),
incremental_authorization_allowed: None,
}),
..item.data
@@ -3683,11 +3740,7 @@ impl TryFrom<types::PaymentsCaptureResponseRouterData<AdyenCaptureResponse>>
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
- connector_response_reference_id: item
- .response
- .merchant_reference
- .clone()
- .or(Some(item.response.psp_reference)),
+ connector_response_reference_id: Some(item.response.reference),
incremental_authorization_allowed: None,
}),
amount_captured: Some(item.response.amount.value),
@@ -3829,7 +3882,9 @@ pub enum WebhookEventCode {
Authorisation,
Refund,
CancelOrRefund,
+ Cancellation,
RefundFailed,
+ RefundReversed,
NotificationOfChargeback,
Chargeback,
ChargebackReversed,
@@ -3846,10 +3901,12 @@ pub fn is_transaction_event(event_code: &WebhookEventCode) -> bool {
matches!(event_code, WebhookEventCode::Authorisation)
}
-pub fn is_capture_event(event_code: &WebhookEventCode) -> bool {
+pub fn is_capture_or_cancel_event(event_code: &WebhookEventCode) -> bool {
matches!(
event_code,
- WebhookEventCode::Capture | WebhookEventCode::CaptureFailed
+ WebhookEventCode::Capture
+ | WebhookEventCode::CaptureFailed
+ | WebhookEventCode::Cancellation
)
}
@@ -3859,6 +3916,7 @@ pub fn is_refund_event(event_code: &WebhookEventCode) -> bool {
WebhookEventCode::Refund
| WebhookEventCode::CancelOrRefund
| WebhookEventCode::RefundFailed
+ | WebhookEventCode::RefundReversed
)
}
@@ -3874,31 +3932,66 @@ pub fn is_chargeback_event(event_code: &WebhookEventCode) -> bool {
)
}
-impl ForeignFrom<(WebhookEventCode, Option<DisputeStatus>)> for webhooks::IncomingWebhookEvent {
- fn foreign_from((code, status): (WebhookEventCode, Option<DisputeStatus>)) -> Self {
- match (code, status) {
- (WebhookEventCode::Authorisation, _) => Self::PaymentIntentSuccess,
- (WebhookEventCode::Refund, _) => Self::RefundSuccess,
- (WebhookEventCode::CancelOrRefund, _) => Self::RefundSuccess,
- (WebhookEventCode::RefundFailed, _) => Self::RefundFailure,
- (WebhookEventCode::NotificationOfChargeback, _) => Self::DisputeOpened,
- (WebhookEventCode::Chargeback, None) => Self::DisputeLost,
- (WebhookEventCode::Chargeback, Some(DisputeStatus::Won)) => Self::DisputeWon,
- (WebhookEventCode::Chargeback, Some(DisputeStatus::Lost)) => Self::DisputeLost,
- (WebhookEventCode::Chargeback, Some(_)) => Self::DisputeOpened,
- (WebhookEventCode::ChargebackReversed, Some(DisputeStatus::Pending)) => {
- Self::DisputeChallenged
+fn is_success_scenario(is_success: String) -> bool {
+ is_success.as_str() == "true"
+}
+
+impl ForeignFrom<(WebhookEventCode, String, Option<DisputeStatus>)>
+ for webhooks::IncomingWebhookEvent
+{
+ fn foreign_from(
+ (code, is_success, dispute_status): (WebhookEventCode, String, Option<DisputeStatus>),
+ ) -> Self {
+ match code {
+ WebhookEventCode::Authorisation => {
+ if is_success_scenario(is_success) {
+ Self::PaymentIntentSuccess
+ } else {
+ Self::PaymentIntentFailure
+ }
+ }
+ WebhookEventCode::Refund | WebhookEventCode::CancelOrRefund => {
+ if is_success_scenario(is_success) {
+ Self::RefundSuccess
+ } else {
+ Self::RefundFailure
+ }
+ }
+ WebhookEventCode::Cancellation => {
+ if is_success_scenario(is_success) {
+ Self::PaymentIntentCancelled
+ } else {
+ Self::PaymentIntentCancelFailure
+ }
}
- (WebhookEventCode::ChargebackReversed, _) => Self::DisputeWon,
- (WebhookEventCode::SecondChargeback, _) => Self::DisputeLost,
- (WebhookEventCode::PrearbitrationWon, Some(DisputeStatus::Pending)) => {
- Self::DisputeOpened
+ WebhookEventCode::RefundFailed | WebhookEventCode::RefundReversed => {
+ Self::RefundFailure
}
- (WebhookEventCode::PrearbitrationWon, _) => Self::DisputeWon,
- (WebhookEventCode::PrearbitrationLost, _) => Self::DisputeLost,
- (WebhookEventCode::Unknown, _) => Self::EventNotSupported,
- (WebhookEventCode::Capture, _) => Self::PaymentIntentSuccess,
- (WebhookEventCode::CaptureFailed, _) => Self::PaymentIntentFailure,
+ WebhookEventCode::NotificationOfChargeback => Self::DisputeOpened,
+ WebhookEventCode::Chargeback => match dispute_status {
+ Some(DisputeStatus::Won) => Self::DisputeWon,
+ Some(DisputeStatus::Lost) | None => Self::DisputeLost,
+ Some(_) => Self::DisputeOpened,
+ },
+ WebhookEventCode::ChargebackReversed => match dispute_status {
+ Some(DisputeStatus::Pending) => Self::DisputeChallenged,
+ _ => Self::DisputeWon,
+ },
+ WebhookEventCode::SecondChargeback => Self::DisputeLost,
+ WebhookEventCode::PrearbitrationWon => match dispute_status {
+ Some(DisputeStatus::Pending) => Self::DisputeOpened,
+ _ => Self::DisputeWon,
+ },
+ WebhookEventCode::PrearbitrationLost => Self::DisputeLost,
+ WebhookEventCode::Capture => {
+ if is_success_scenario(is_success) {
+ Self::PaymentIntentCaptureSuccess
+ } else {
+ Self::PaymentIntentCaptureFailure
+ }
+ }
+ WebhookEventCode::CaptureFailed => Self::PaymentIntentCaptureFailure,
+ WebhookEventCode::Unknown => Self::EventNotSupported,
}
}
}
@@ -3949,7 +4042,13 @@ impl From<AdyenNotificationRequestItemWH> for Response {
psp_reference: notif.psp_reference,
merchant_reference: notif.merchant_reference,
result_code: match notif.success.as_str() {
- "true" => AdyenStatus::Authorised,
+ "true" => {
+ if notif.event_code == WebhookEventCode::Cancellation {
+ AdyenStatus::Cancelled
+ } else {
+ AdyenStatus::Authorised
+ }
+ }
_ => AdyenStatus::Refused,
},
amount: Some(Amount {
diff --git a/crates/router/src/connector/nuvei/transformers.rs b/crates/router/src/connector/nuvei/transformers.rs
index d5dd6e813ae..13d522b86cc 100644
--- a/crates/router/src/connector/nuvei/transformers.rs
+++ b/crates/router/src/connector/nuvei/transformers.rs
@@ -615,6 +615,9 @@ impl TryFrom<api_models::enums::BankNames> for NuveiBIC {
| api_models::enums::BankNames::Starling
| api_models::enums::BankNames::TsbBank
| api_models::enums::BankNames::TescoBank
+ | api_models::enums::BankNames::Yoursafe
+ | api_models::enums::BankNames::N26
+ | api_models::enums::BankNames::NationaleNederlanden
| api_models::enums::BankNames::UlsterBank => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Nuvei"),
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index 87886c2c861..2b87d64c6ac 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -1695,6 +1695,7 @@ pub(crate) fn validate_auth_and_metadata_type(
}
api_enums::Connector::Adyen => {
adyen::transformers::AdyenAuthType::try_from(val)?;
+ adyen::transformers::AdyenConnectorMetadataObject::try_from(connector_meta_data)?;
Ok(())
}
api_enums::Connector::Airwallex => {
diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs
index 81dfb7127db..ed96feb2b5e 100644
--- a/crates/router/src/core/payments/operations/payment_status.rs
+++ b/crates/router/src/core/payments/operations/payment_status.rs
@@ -238,7 +238,7 @@ async fn get_tracker_for_sync<
operation: Op,
storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsRetrieveRequest, Ctx>> {
- let (payment_intent, payment_attempt, currency, amount);
+ let (payment_intent, mut payment_attempt, currency, amount);
(payment_intent, payment_attempt) = get_payment_intent_payment_attempt(
db,
@@ -274,6 +274,8 @@ async fn get_tracker_for_sync<
)
.await?;
+ payment_attempt.encoded_data = request.param.clone();
+
let attempts = match request.expand_attempts {
Some(true) => {
Some(db
diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml
index 2f35958ae6d..aa0d75d609f 100644
--- a/loadtest/config/development.toml
+++ b/loadtest/config/development.toml
@@ -191,6 +191,10 @@ open_banking_uk = {country = "DE,GB,AT,BE,CY,EE,ES,FI,FR,GR,HR,IE,IT,LT,LU,LV,MT
[pm_filters.adyen]
boleto = { country = "BR", currency = "BRL" }
+sofort = { country = "AT,BE,DE,ES,CH,NL", currency = "CHF,EUR"}
+paypal = { country = "AU,NZ,CN,JP,HK,MY,TH,KR,PH,ID,AE,KW,BR,ES,GB,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,FI,RO,HR,UA,MT,SI,GI,PT,IE,CZ,EE,LT,LV,IT,PL,IS,CA,US", currency = "AUD,BRL,CAD,CZK,DKK,EUR,HKD,HUF,INR,JPY,MYR,MXN,NZD,NOK,PHP,PLN,RUB,GBP,SGD,SEK,CHF,THB,USD" }
+klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NO,PL,PT,RO,ES,SE,CH,NL,GB,US", currency = "AUD,EUR,CAD,CZK,DKK,NOK,PLN,RON,SEK,CHF,GBP,USD"}
+ideal = { country = "NL", currency = "EUR" }
[pm_filters.zen]
credit = { not_available_flows = { capture_method = "manual" } }
diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json
index 30e75c028d5..ce4c4c2a0ef 100644
--- a/openapi/openapi_spec.json
+++ b/openapi/openapi_spec.json
@@ -5092,7 +5092,10 @@
"starling",
"tsb_bank",
"tesco_bank",
- "ulster_bank"
+ "ulster_bank",
+ "yoursafe",
+ "n26",
+ "nationale_nederlanden"
]
},
"BankRedirectBilling": {
|
2024-02-29T12:17:48Z
|
## 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 -->
- Add production live endpoint for Adyen
- Fix webhooks status mapping
- Fix redirection data not getting populated in encoded data
- Add Live Bank Names for Ideal
- Add Currency, Country config for `klarna, ideal, sofort, paypal`
### 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`
-->
- Added configs for Currency, Country for `klarna, ideal, sofort, paypal`
- Update payment endpoints for production
## 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).
-->
#3614
#3903
## 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 flows of Adyen are required to be tested as base url and status mapping along with webhooks is changed.
- Test Webhooks Extensively, the outgoing webhooks and the status updates webhooks are triggering.
Please use the postman collection defined here: `postman/collection-json/adyen_uk.postman_collection.json`
## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
7db499d8a9388b9a3674f7fa130bc389151840ec
|
|
juspay/hyperswitch
|
juspay__hyperswitch-3893
|
Bug: [FEATURE] [PLACETOPAY] Connector audit
### Feature Description
Connector placetopay needs to be audited.
### Possible Implementation
Connector placetopay needs to be audited.
### 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/placetopay.rs b/crates/router/src/connector/placetopay.rs
index 81255f450e5..c28fed1fede 100644
--- a/crates/router/src/connector/placetopay.rs
+++ b/crates/router/src/connector/placetopay.rs
@@ -119,8 +119,8 @@ impl ConnectorValidation for Placetopay {
) -> CustomResult<(), errors::ConnectorError> {
let capture_method = capture_method.unwrap_or_default();
match capture_method {
- enums::CaptureMethod::Manual => Ok(()),
- enums::CaptureMethod::Automatic
+ enums::CaptureMethod::Automatic => Ok(()),
+ enums::CaptureMethod::Manual
| enums::CaptureMethod::ManualMultiple
| enums::CaptureMethod::Scheduled => Err(utils::construct_not_supported_error_report(
capture_method,
@@ -615,7 +615,7 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
Ok(Some(
services::RequestBuilder::new()
- .method(services::Method::Get)
+ .method(services::Method::Post)
.url(&types::RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundSyncType::get_headers(self, req, connectors)?)
diff --git a/crates/router/src/connector/placetopay/transformers.rs b/crates/router/src/connector/placetopay/transformers.rs
index f1c054b960b..e5dedf6ded0 100644
--- a/crates/router/src/connector/placetopay/transformers.rs
+++ b/crates/router/src/connector/placetopay/transformers.rs
@@ -206,30 +206,43 @@ impl TryFrom<&types::ConnectorAuthType> for PlacetopayAuthType {
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
-pub enum PlacetopayStatus {
+pub enum PlacetopayTransactionStatus {
Ok,
Failed,
Approved,
+ // ApprovedPartial,
+ // PartialExpired,
Rejected,
Pending,
PendingValidation,
PendingProcess,
+ // Refunded,
+ // Reversed,
+ Error,
+ // Unknown,
+ // Manual,
+ // Dispute,
+ //The statuses that are commented out are awaiting clarification on the connector.
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlacetopayStatusResponse {
- status: PlacetopayStatus,
+ status: PlacetopayTransactionStatus,
}
-impl From<PlacetopayStatus> for enums::AttemptStatus {
- fn from(item: PlacetopayStatus) -> Self {
+impl From<PlacetopayTransactionStatus> for enums::AttemptStatus {
+ fn from(item: PlacetopayTransactionStatus) -> Self {
match item {
- PlacetopayStatus::Approved | PlacetopayStatus::Ok => Self::Authorized,
- PlacetopayStatus::Failed | PlacetopayStatus::Rejected => Self::Failure,
- PlacetopayStatus::Pending
- | PlacetopayStatus::PendingValidation
- | PlacetopayStatus::PendingProcess => Self::Authorizing,
+ PlacetopayTransactionStatus::Approved | PlacetopayTransactionStatus::Ok => {
+ Self::Charged
+ }
+ PlacetopayTransactionStatus::Failed
+ | PlacetopayTransactionStatus::Rejected
+ | PlacetopayTransactionStatus::Error => Self::Failure,
+ PlacetopayTransactionStatus::Pending
+ | PlacetopayTransactionStatus::PendingValidation
+ | PlacetopayTransactionStatus::PendingProcess => Self::Pending,
}
}
}
@@ -239,6 +252,7 @@ impl From<PlacetopayStatus> for enums::AttemptStatus {
pub struct PlacetopayPaymentsResponse {
status: PlacetopayStatusResponse,
internal_reference: u64,
+ authorization: Option<String>,
}
impl<F, T>
@@ -263,7 +277,11 @@ impl<F, T>
),
redirection_data: None,
mandate_reference: None,
- connector_metadata: None,
+ connector_metadata: item
+ .response
+ .authorization
+ .clone()
+ .map(|authorization| serde_json::json!(authorization)),
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
@@ -281,55 +299,90 @@ pub struct PlacetopayRefundRequest {
auth: PlacetopayAuth,
internal_reference: u64,
action: PlacetopayNextAction,
+ authorization: Option<String>,
}
impl<F> TryFrom<&types::RefundsRouterData<F>> for PlacetopayRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> {
- let auth = PlacetopayAuth::try_from(&item.connector_auth_type)?;
- let internal_reference = item
- .request
- .connector_transaction_id
- .parse::<u64>()
- .into_report()
- .change_context(errors::ConnectorError::RequestEncodingFailed)?;
- let action = PlacetopayNextAction::Refund;
-
- Ok(Self {
- auth,
- internal_reference,
- action,
- })
+ if item.request.refund_amount == item.request.payment_amount {
+ let auth = PlacetopayAuth::try_from(&item.connector_auth_type)?;
+
+ let internal_reference = item
+ .request
+ .connector_transaction_id
+ .parse::<u64>()
+ .into_report()
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;
+ let action = PlacetopayNextAction::Reverse;
+ let authorization = match item.request.connector_metadata.clone() {
+ Some(metadata) => metadata.as_str().map(|auth| auth.to_string()),
+ None => None,
+ };
+ Ok(Self {
+ auth,
+ internal_reference,
+ action,
+ authorization,
+ })
+ } else {
+ Err(errors::ConnectorError::NotSupported {
+ message: "Partial Refund".to_string(),
+ connector: "placetopay",
+ }
+ .into())
+ }
}
}
impl From<PlacetopayRefundStatus> for enums::RefundStatus {
fn from(item: PlacetopayRefundStatus) -> Self {
match item {
- PlacetopayRefundStatus::Refunded => Self::Success,
- PlacetopayRefundStatus::Failed | PlacetopayRefundStatus::Rejected => Self::Failure,
- PlacetopayRefundStatus::Pending | PlacetopayRefundStatus::PendingProcess => {
- Self::Pending
- }
+ PlacetopayRefundStatus::Ok
+ | PlacetopayRefundStatus::Approved
+ | PlacetopayRefundStatus::Refunded => Self::Success,
+ PlacetopayRefundStatus::Failed
+ | PlacetopayRefundStatus::Rejected
+ | PlacetopayRefundStatus::Error => Self::Failure,
+ PlacetopayRefundStatus::Pending
+ | PlacetopayRefundStatus::PendingProcess
+ | PlacetopayRefundStatus::PendingValidation => Self::Pending,
}
}
}
-#[derive(Debug, Deserialize, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct PlacetopayRefundResponse {
- status: PlacetopayRefundStatus,
- internal_reference: u64,
-}
-
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PlacetopayRefundStatus {
- Refunded,
- Rejected,
+ Ok,
Failed,
+ Approved,
+ // ApprovedPartial,
+ // PartialExpired,
+ Rejected,
Pending,
+ PendingValidation,
PendingProcess,
+ Refunded,
+ // Reversed,
+ Error,
+ // Unknown,
+ // Manual,
+ // Dispute,
+ //The statuses that are commented out are awaiting clarification on the connector.
+}
+
+#[derive(Debug, Deserialize, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct PlacetopayRefundStatusResponse {
+ status: PlacetopayRefundStatus,
+}
+
+#[derive(Debug, Deserialize, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct PlacetopayRefundResponse {
+ status: PlacetopayRefundStatusResponse,
+ internal_reference: u64,
}
impl TryFrom<types::RefundsResponseRouterData<api::Execute, PlacetopayRefundResponse>>
@@ -342,7 +395,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, PlacetopayRefundResp
Ok(Self {
response: Ok(types::RefundsResponseData {
connector_refund_id: item.response.internal_reference.to_string(),
- refund_status: enums::RefundStatus::from(item.response.status),
+ refund_status: enums::RefundStatus::from(item.response.status.status),
}),
..item.data
})
@@ -383,7 +436,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, PlacetopayRefundRespon
Ok(Self {
response: Ok(types::RefundsResponseData {
connector_refund_id: item.response.internal_reference.to_string(),
- refund_status: enums::RefundStatus::from(item.response.status),
+ refund_status: enums::RefundStatus::from(item.response.status.status),
}),
..item.data
})
@@ -447,6 +500,7 @@ pub struct PlacetopayNextActionRequest {
#[serde(rename_all = "camelCase")]
pub enum PlacetopayNextAction {
Refund,
+ Reverse,
Void,
Process,
Checkout,
|
2024-02-29T10:28: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 -->
- The authorization field retrieved during payments for Placetopay is now utilized in refund requests.
The following features have been removed as they are not supported by the connector:
- Manual authorization
- Partial refunds
### 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/3893
## 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 following flows need to be tested for connector placetopay:
1. Authorization(Auto-capture)
Request:
```curl
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: API_KEY_HERE' \
--data '{
"amount":320320,
"currency": "COP",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"customer_id": "deepanshu",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4110770010002837",
"card_exp_month": "02",
"card_exp_year": "26",
"card_holder_name": "joseph",
"card_cvc": "837"
}
},
"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",
"ip_address": "127.2.2.0"
}
}'
```
Response:
```json
{
"payment_id": "pay_6Ra7qnW72e498RBrNgGs",
"merchant_id": "merchant_1707896273",
"status": "succeeded",
"amount": 320320,
"net_amount": 320320,
"amount_capturable": 0,
"amount_received": 320320,
"connector": "placetopay",
"client_secret": "pay_6Ra7qnW72e498RBrNgGs_secret_bqPRBHD9bFu6HzOzwkR1",
"created": "2024-03-01T09:31:37.556Z",
"currency": "COP",
"customer_id": "deepanshu",
"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": "2837",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "411077",
"card_extended_bin": "41107700",
"card_exp_month": "02",
"card_exp_year": "26",
"card_holder_name": "joseph"
}
},
"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": "deepanshu",
"created_at": 1709285497,
"expires": 1709289097,
"secret": "epk_f80f7b586ab64a1eae89501b68c09d00"
},
"manual_retry_allowed": false,
"connector_transaction_id": "1598433361",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": null,
"payment_link": null,
"profile_id": "pro_aAoX3JP7KaSPBqGXewox",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_UBdzUxzIT2eGEGnWq7wd",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"expires_on": "2024-03-01T09:46:37.556Z",
"fingerprint": null
}
```
2. Authorization(Manual capture)
Request:
```curl
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: API_KEY_HERE' \
--data '{
"amount":320320,
"currency": "COP",
"confirm": true,
"capture_method": "manual",
"capture_on": "2022-09-10T10:11:12Z",
"customer_id": "deepanshu",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4110770010002837",
"card_exp_month": "02",
"card_exp_year": "26",
"card_holder_name": "joseph",
"card_cvc": "837"
}
},
"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",
"ip_address": "127.2.2.0"
}
}'
```
Response:
```json
{
"error": {
"type": "invalid_request",
"message": "Payment method type not supported",
"code": "HE_03",
"reason": "manual is not supported by placetopay"
}
}
```
3. Refunds
Request:
```curl
curl --location 'http://localhost:8080/refunds' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: API_KEY_HERE' \
--data '{
"payment_id": "pay_6Ra7qnW72e498RBrNgGs",
"refund_type": "instant"
}'
```
Response:
```json
{
"refund_id": "ref_dFvFk3gvAKMsWEyWq81d",
"payment_id": "pay_6Ra7qnW72e498RBrNgGs",
"amount": 320320,
"currency": "COP",
"status": "succeeded",
"reason": null,
"metadata": null,
"error_message": null,
"error_code": null,
"created_at": "2024-03-01T09:31:45.539Z",
"updated_at": "2024-03-01T09:31:45.539Z",
"connector": "placetopay",
"profile_id": "pro_aAoX3JP7KaSPBqGXewox",
"merchant_connector_id": "mca_UBdzUxzIT2eGEGnWq7wd"
}
```
3. Partial Refunds
Request:
```curl
curl --location 'http://localhost:8080/refunds' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: API_KEY_HERE' \
--data '{
"payment_id": "pay_T5RoR7gNvWAilXweIUOo",
"amount": 600,
"reason": "Customer returned product",
"refund_type": "instant",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}'
```
Response:
```json
{
"error": {
"type": "invalid_request",
"message": "Refund failed while processing with connector. Retry refund",
"code": "CE_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`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
f132527490a7d8cd8469573d8e6856f33974959f
|
|
juspay/hyperswitch
|
juspay__hyperswitch-3878
|
Bug: [FEATURE] : [Noon] mask pii information in connector request and response
### Feature Description
Mask pii information passed and received in the connector request and response
### Possible Implementation
Refactor all sensitive response and request fields secret
### 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/noon/transformers.rs b/crates/router/src/connector/noon/transformers.rs
index fff99109b28..fdcb2ad5afc 100644
--- a/crates/router/src/connector/noon/transformers.rs
+++ b/crates/router/src/connector/noon/transformers.rs
@@ -1,6 +1,6 @@
use common_utils::{ext_traits::Encode, pii};
use error_stack::{IntoReport, ResultExt};
-use masking::{PeekInterface, Secret};
+use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
@@ -124,7 +124,7 @@ pub struct NoonConfiguration {
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NoonSubscription {
- subscription_identifier: String,
+ subscription_identifier: Secret<String>,
}
#[derive(Debug, Serialize)]
@@ -230,9 +230,9 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for NoonPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {
let (payment_data, currency, category) = match item.request.connector_mandate_id() {
- Some(subscription_identifier) => (
+ Some(mandate_id) => (
NoonPaymentData::Subscription(NoonSubscription {
- subscription_identifier,
+ subscription_identifier: Secret::new(mandate_id),
}),
None,
None,
@@ -512,7 +512,7 @@ impl ForeignFrom<(NoonPaymentStatus, Self)> for enums::AttemptStatus {
#[derive(Debug, Serialize, Deserialize)]
pub struct NoonSubscriptionObject {
- identifier: String,
+ identifier: Secret<String>,
}
#[derive(Default, Debug, Serialize, Deserialize)]
@@ -566,7 +566,7 @@ impl<F, T>
.result
.subscription
.map(|subscription_data| types::MandateReference {
- connector_mandate_id: Some(subscription_data.identifier),
+ connector_mandate_id: Some(subscription_data.identifier.expose()),
payment_method_id: None,
});
Ok(Self {
@@ -678,7 +678,7 @@ impl TryFrom<&types::MandateRevokeRouterData> for NoonRevokeMandateRequest {
Ok(Self {
api_operation: NoonApiOperations::CancelSubscription,
subscription: NoonSubscriptionObject {
- identifier: item.request.get_connector_mandate_id()?,
+ identifier: Secret::new(item.request.get_connector_mandate_id()?),
},
})
}
|
2024-02-28T13:57:26Z
|
## 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 -->
Mask pii information passed and received in the connector request and response for Noon.
## Test Case
1. Create a mandate payment with Noon
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_DSA7zgwLkTw5bHT6khsixyQNDlvsM6HDvyhxwMulGlRk8gnjJwejcmvOCniHFWT6' \
--data-raw '{
"amount": 10000,
"currency": "AED",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"customer_id": "c1",
"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://google.com",
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "AE",
"first_name": "John",
"last_name": "Doe"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "AE",
"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"
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"pru": "value1"
},
"payment_method": "card",
"payment_method_data": {
"card": {
"card_number": "4000000000002503",
"card_exp_month": "01",
"card_exp_year": "2026",
"card_holder_name": "Joseph Doe",
"card_cvc": "124"
}
},
"setup_future_usage": "off_session",
"mandate_data": {
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "13.232.74.226",
"user_agent": "amet irure esse"
}
}
,
"mandate_type": {
"multi_use": {
"amount": 700,
"currency": "AED"
}
}
},
"connector_metadata": {
"noon": {
"order_category": "pay"
}
}
}'
```
2. Create a MIT
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key:{{}}' \
--data '{
"amount": 700,
"currency": "AED",
"off_session": true,
"confirm": true,
"capture_method": "automatic",
"description": "Initiated by merchant",
"mandate_id": "man_spNAzYmZ2Sq3119WEe4q",
"customer_id": "c1",
"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"
}
}
}'
```
3. Check if `subscription_data.identifier` in the `masked_response` is masked
```
curl --location '{{base_url}}/analytics/v1/connector_event_logs?type=Payment&payment_id={{payment_id}}' \
--header 'sec-ch-ua: "Not A(Brand";v="99", "Google Chrome";v="121", "Chromium";v="121"' \
--header 'sec-ch-ua-mobile: ?0' \
--header 'authorization: Bearer JWT_token' \
--header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36' \
--header 'Content-Type: application/json' \
--header 'Referer: https://integ.hyperswitch.io/' \
--header 'api-key: {{api-key}}' \
--header 'sec-ch-ua-platform: "macOS"'
```
Response
```
"masked_response\":\"{\\\"result\\\":{\\\"order\\\":{\\\"status\\\":\\\"CAPTURED\\\",\\\"id\\\":510639573125,\\\"errorCode\\\":0,\\\"errorMessage\\\":null,\\\"reference\\\":\\\"pay_7WNBRRI9bCY29pnKwDn8_1\\\"},\\\"checkoutData\\\":null,\\\"subscription\\\":{\\\"identifier\\\":\\\"*** alloc::string::String ***\\\"}}
```
```
"masked_response\":\"{\\\"result\\\":{\\\"order\\\":{\\\"status\\\":\\\"CAPTURED\\\",\\\"id\\\":291984139449,\\\"errorCode\\\":0,\\\"errorMessage\\\":null,\\\"reference\\\":\\\"pay_LqEgkjiIOHZfT7ax1QHl_1\\\"},\\\"checkoutData\\\":null,\\\"subscription\\\":{\\\"identifier\\\":\\\"*** alloc::string::String ***\\\"}}}
```
## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
032d58cdbbf388cf25cbf2e43b0117b83f7d076d
|
|
juspay/hyperswitch
|
juspay__hyperswitch-3895
|
Bug: refactor: change create and update role apis to respond with role info
|
diff --git a/crates/api_models/src/events/user_role.rs b/crates/api_models/src/events/user_role.rs
index aee2b3fb66c..0d42d1de7d6 100644
--- a/crates/api_models/src/events/user_role.rs
+++ b/crates/api_models/src/events/user_role.rs
@@ -3,7 +3,8 @@ use common_utils::events::{ApiEventMetric, ApiEventsType};
use crate::user_role::{
role::{
CreateRoleRequest, GetRoleFromTokenResponse, GetRoleRequest, ListRolesResponse,
- RoleInfoResponse, RoleInfoWithPermissionsResponse, UpdateRoleRequest,
+ RoleInfoResponse, RoleInfoWithGroupsResponse, RoleInfoWithPermissionsResponse,
+ UpdateRoleRequest,
},
AcceptInvitationRequest, AuthorizationInfoResponse, DeleteUserRoleRequest,
TransferOrgOwnershipRequest, UpdateUserRoleRequest,
@@ -21,5 +22,6 @@ common_utils::impl_misc_api_event_type!(
UpdateRoleRequest,
ListRolesResponse,
RoleInfoResponse,
- GetRoleFromTokenResponse
+ GetRoleFromTokenResponse,
+ RoleInfoWithGroupsResponse
);
diff --git a/crates/router/src/core/user_role/role.rs b/crates/router/src/core/user_role/role.rs
index c3d534f8860..6aa226cd933 100644
--- a/crates/router/src/core/user_role/role.rs
+++ b/crates/router/src/core/user_role/role.rs
@@ -57,14 +57,18 @@ pub async fn create_role(
state: AppState,
user_from_token: UserFromToken,
req: role_api::CreateRoleRequest,
-) -> UserResponse<()> {
+) -> UserResponse<role_api::RoleInfoWithGroupsResponse> {
let now = common_utils::date_time::now();
- let role_name = RoleName::new(req.role_name)?.get_role_name();
+ let role_name = RoleName::new(req.role_name)?;
- if req.groups.is_empty() {
- return Err(UserErrors::InvalidRoleOperation.into())
- .attach_printable("Role groups cannot be empty");
- }
+ utils::user_role::validate_role_groups(&req.groups)?;
+ utils::user_role::validate_role_name(
+ &state,
+ &role_name,
+ &user_from_token.merchant_id,
+ &user_from_token.org_id,
+ )
+ .await?;
if matches!(req.role_scope, RoleScope::Organization)
&& user_from_token.role_id != consts::user_role::ROLE_ID_ORGANIZATION_ADMIN
@@ -73,19 +77,11 @@ pub async fn create_role(
.attach_printable("Non org admin user creating org level role");
}
- utils::user_role::is_role_name_already_present_for_merchant(
- &state,
- &role_name,
- &user_from_token.merchant_id,
- &user_from_token.org_id,
- )
- .await?;
-
- state
+ let role = state
.store
.insert_role(RoleNew {
role_id: generate_id_with_default_len("role"),
- role_name,
+ role_name: role_name.get_role_name(),
merchant_id: user_from_token.merchant_id,
org_id: user_from_token.org_id,
groups: req.groups,
@@ -98,7 +94,14 @@ pub async fn create_role(
.await
.to_duplicate_response(UserErrors::RoleNameAlreadyExists)?;
- Ok(ApplicationResponse::StatusOk)
+ Ok(ApplicationResponse::Json(
+ role_api::RoleInfoWithGroupsResponse {
+ groups: role.groups,
+ role_id: role.role_id,
+ role_name: role.role_name,
+ role_scope: role.scope,
+ },
+ ))
}
// TODO: To be deprecated once groups are stable
@@ -260,15 +263,11 @@ pub async fn update_role(
user_from_token: UserFromToken,
req: role_api::UpdateRoleRequest,
role_id: &str,
-) -> UserResponse<()> {
- let role_name = req
- .role_name
- .map(RoleName::new)
- .transpose()?
- .map(RoleName::get_role_name);
+) -> UserResponse<role_api::RoleInfoWithGroupsResponse> {
+ let role_name = req.role_name.map(RoleName::new).transpose()?;
if let Some(ref role_name) = role_name {
- utils::user_role::is_role_name_already_present_for_merchant(
+ utils::user_role::validate_role_name(
&state,
role_name,
&user_from_token.merchant_id,
@@ -277,6 +276,10 @@ pub async fn update_role(
.await?;
}
+ if let Some(ref groups) = req.groups {
+ utils::user_role::validate_role_groups(groups)?;
+ }
+
let role_info = roles::RoleInfo::from_role_id(
&state,
role_id,
@@ -290,23 +293,16 @@ pub async fn update_role(
&& user_from_token.role_id != consts::user_role::ROLE_ID_ORGANIZATION_ADMIN
{
return Err(UserErrors::InvalidRoleOperation.into())
- .attach_printable("Non org admin user creating org level role");
+ .attach_printable("Non org admin user changing org level role");
}
- if let Some(ref groups) = req.groups {
- if groups.is_empty() {
- return Err(UserErrors::InvalidRoleOperation.into())
- .attach_printable("role groups cannot be empty");
- }
- }
-
- state
+ let updated_role = state
.store
.update_role_by_role_id(
role_id,
RoleUpdate::UpdateDetails {
groups: req.groups,
- role_name,
+ role_name: role_name.map(RoleName::get_role_name),
last_modified_at: common_utils::date_time::now(),
last_modified_by: user_from_token.user_id,
},
@@ -316,5 +312,12 @@ pub async fn update_role(
blacklist::insert_role_in_blacklist(&state, role_id).await?;
- Ok(ApplicationResponse::StatusOk)
+ Ok(ApplicationResponse::Json(
+ role_api::RoleInfoWithGroupsResponse {
+ groups: updated_role.groups,
+ role_id: updated_role.role_id,
+ role_name: updated_role.role_name,
+ role_scope: updated_role.scope,
+ },
+ ))
}
diff --git a/crates/router/src/services/authorization/roles/predefined_roles.rs b/crates/router/src/services/authorization/roles/predefined_roles.rs
index 9accf094ea4..568af6e19fd 100644
--- a/crates/router/src/services/authorization/roles/predefined_roles.rs
+++ b/crates/router/src/services/authorization/roles/predefined_roles.rs
@@ -26,7 +26,7 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(|
PermissionGroup::OrganizationManage,
],
role_id: consts::user_role::ROLE_ID_INTERNAL_ADMIN.to_string(),
- role_name: "Internal Admin".to_string(),
+ role_name: "internal_admin".to_string(),
scope: RoleScope::Organization,
is_invitable: false,
is_deletable: false,
@@ -46,7 +46,7 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(|
PermissionGroup::MerchantDetailsView,
],
role_id: consts::user_role::ROLE_ID_INTERNAL_VIEW_ONLY_USER.to_string(),
- role_name: "Internal View Only".to_string(),
+ role_name: "internal_view_only".to_string(),
scope: RoleScope::Organization,
is_invitable: false,
is_deletable: false,
@@ -73,7 +73,7 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(|
PermissionGroup::OrganizationManage,
],
role_id: consts::user_role::ROLE_ID_ORGANIZATION_ADMIN.to_string(),
- role_name: "Organization Admin".to_string(),
+ role_name: "organization_admin".to_string(),
scope: RoleScope::Organization,
is_invitable: false,
is_deletable: false,
@@ -100,7 +100,7 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(|
PermissionGroup::MerchantDetailsManage,
],
role_id: consts::user_role::ROLE_ID_MERCHANT_ADMIN.to_string(),
- role_name: "Admin".to_string(),
+ role_name: "admin".to_string(),
scope: RoleScope::Organization,
is_invitable: true,
is_deletable: true,
@@ -120,7 +120,7 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(|
PermissionGroup::MerchantDetailsView,
],
role_id: consts::user_role::ROLE_ID_MERCHANT_VIEW_ONLY.to_string(),
- role_name: "View Only".to_string(),
+ role_name: "view_only".to_string(),
scope: RoleScope::Organization,
is_invitable: true,
is_deletable: true,
@@ -139,7 +139,7 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(|
PermissionGroup::MerchantDetailsView,
],
role_id: consts::user_role::ROLE_ID_MERCHANT_IAM_ADMIN.to_string(),
- role_name: "IAM".to_string(),
+ role_name: "iam".to_string(),
scope: RoleScope::Organization,
is_invitable: true,
is_deletable: true,
@@ -159,7 +159,7 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(|
PermissionGroup::MerchantDetailsManage,
],
role_id: consts::user_role::ROLE_ID_MERCHANT_DEVELOPER.to_string(),
- role_name: "Developer".to_string(),
+ role_name: "developer".to_string(),
scope: RoleScope::Organization,
is_invitable: true,
is_deletable: true,
@@ -180,7 +180,7 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(|
PermissionGroup::MerchantDetailsView,
],
role_id: consts::user_role::ROLE_ID_MERCHANT_OPERATOR.to_string(),
- role_name: "Operator".to_string(),
+ role_name: "operator".to_string(),
scope: RoleScope::Organization,
is_invitable: true,
is_deletable: true,
@@ -198,7 +198,7 @@ pub static PREDEFINED_ROLES: Lazy<HashMap<&'static str, RoleInfo>> = Lazy::new(|
PermissionGroup::MerchantDetailsView,
],
role_id: consts::user_role::ROLE_ID_MERCHANT_CUSTOMER_SUPPORT.to_string(),
- role_name: "Customer Support".to_string(),
+ role_name: "customer_support".to_string(),
scope: RoleScope::Organization,
is_invitable: true,
is_deletable: true,
diff --git a/crates/router/src/utils/user_role.rs b/crates/router/src/utils/user_role.rs
index 8ae65ce86e0..bb83b82f2da 100644
--- a/crates/router/src/utils/user_role.rs
+++ b/crates/router/src/utils/user_role.rs
@@ -1,10 +1,12 @@
use api_models::user_role as user_role_api;
+use common_enums::PermissionGroup;
use error_stack::ResultExt;
use crate::{
core::errors::{UserErrors, UserResult},
routes::AppState,
- services::authorization::permissions::Permission,
+ services::authorization::{permissions::Permission, roles},
+ types::domain,
};
impl From<Permission> for user_role_api::Permission {
@@ -40,23 +42,44 @@ impl From<Permission> for user_role_api::Permission {
}
}
-pub async fn is_role_name_already_present_for_merchant(
+pub fn validate_role_groups(groups: &[PermissionGroup]) -> UserResult<()> {
+ if groups.is_empty() {
+ return Err(UserErrors::InvalidRoleOperation.into())
+ .attach_printable("Role groups cannot be empty");
+ }
+
+ if groups.contains(&PermissionGroup::OrganizationManage) {
+ return Err(UserErrors::InvalidRoleOperation.into())
+ .attach_printable("Organization manage group cannot be added to role");
+ }
+
+ Ok(())
+}
+
+pub async fn validate_role_name(
state: &AppState,
- role_name: &str,
+ role_name: &domain::RoleName,
merchant_id: &str,
org_id: &str,
) -> UserResult<()> {
- let role_name_list: Vec<String> = state
+ let role_name_str = role_name.clone().get_role_name();
+
+ let is_present_in_predefined_roles = roles::predefined_roles::PREDEFINED_ROLES
+ .iter()
+ .any(|(_, role_info)| role_info.get_role_name() == role_name_str);
+
+ // TODO: Create and use find_by_role_name to make this efficient
+ let is_present_in_custom_roles = state
.store
.list_all_roles(merchant_id, org_id)
.await
.change_context(UserErrors::InternalServerError)?
.iter()
- .map(|role| role.role_name.to_owned())
- .collect();
+ .any(|role| role.role_name == role_name_str);
- if role_name_list.contains(&role_name.to_string()) {
+ if is_present_in_predefined_roles || is_present_in_custom_roles {
return Err(UserErrors::RoleNameAlreadyExists.into());
}
+
Ok(())
}
|
2024-02-29T10:55:41Z
|
## 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 modifies create and update role APIs. The APIs will now respond with the role created/updated respectively.
This PR also changes the names of predefined roles to snake case.
### 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 #3895
## 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 role
- `organization_manage` cannot be sent in groups.
- `role_name` should not be present in any other roles that merchant has access to.
- Non `org_admin` won't be able to create a role with `role_scope` as `organization`
- `groups` should not be empty.
```
curl --location 'http://localhost:8080/user/role' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer JWT' \
--data '{
"role_name": "admin",
"groups": ["users_manage"],
"role_scope": "organization"
}'
```
- Response:
```
{
"role_id": "role_KLw0K0psguhVX8FhvIuv",
"groups": [
"users_manage"
],
"role_name": "admin1",
"role_scope": "organization"
}
```
2. Update role
- `organization_manage` cannot be sent in groups.
- `role_name` should not be present in any other roles that merchant has access to.
- Non `org_admin` won't be able to update a role with `role_scope` as `organization`
- `groups` should not be empty.
```
curl --location 'http://localhost:8080/user/role/role_KLw0K0psguhVX8FhvIuv' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer JWT' \
--data '{
"groups": ["users_view"]
}'
```
- Response:
```
{
"role_id": "role_KLw0K0psguhVX8FhvIuv",
"groups": [
"users_view"
],
"role_name": "admin1",
"role_scope": "organization"
}
```
## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
de7f400c07d85b97340255556b39383648a0fd9f
|
|
juspay/hyperswitch
|
juspay__hyperswitch-3887
|
Bug: [Analytics] - Disputes fix psql
|
diff --git a/crates/diesel_models/src/dispute.rs b/crates/diesel_models/src/dispute.rs
index 9bdac332295..eae8281a99d 100644
--- a/crates/diesel_models/src/dispute.rs
+++ b/crates/diesel_models/src/dispute.rs
@@ -29,6 +29,7 @@ pub struct DisputeNew {
pub evidence: Option<Secret<serde_json::Value>>,
pub profile_id: Option<String>,
pub merchant_connector_id: Option<String>,
+ pub dispute_amount: i64,
}
#[derive(Clone, Debug, PartialEq, Serialize, Identifiable, Queryable)]
@@ -59,6 +60,7 @@ pub struct Dispute {
pub evidence: Secret<serde_json::Value>,
pub profile_id: Option<String>,
pub merchant_connector_id: Option<String>,
+ pub dispute_amount: i64,
}
#[derive(Debug)]
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index 9e72d8dc21d..9db9f8c2d43 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -295,6 +295,7 @@ diesel::table! {
profile_id -> Nullable<Varchar>,
#[max_length = 32]
merchant_connector_id -> Nullable<Varchar>,
+ dispute_amount -> Int8,
}
}
diff --git a/crates/router/src/core/webhooks.rs b/crates/router/src/core/webhooks.rs
index ef313b62228..9ec8de21f94 100644
--- a/crates/router/src/core/webhooks.rs
+++ b/crates/router/src/core/webhooks.rs
@@ -352,7 +352,7 @@ pub async fn get_or_update_dispute_object(
let dispute_id = generate_id(consts::ID_LENGTH, "dp");
let new_dispute = diesel_models::dispute::DisputeNew {
dispute_id,
- amount: dispute_details.amount,
+ amount: dispute_details.amount.clone(),
currency: dispute_details.currency,
dispute_stage: dispute_details.dispute_stage,
dispute_status: event_type
@@ -374,6 +374,7 @@ pub async fn get_or_update_dispute_object(
profile_id: Some(business_profile.profile_id.clone()),
evidence: None,
merchant_connector_id: payment_attempt.merchant_connector_id.clone(),
+ dispute_amount: dispute_details.amount.parse::<i64>().unwrap_or(0),
};
state
.store
diff --git a/crates/router/src/db/dispute.rs b/crates/router/src/db/dispute.rs
index 0c34123b6f3..b0d0594c013 100644
--- a/crates/router/src/db/dispute.rs
+++ b/crates/router/src/db/dispute.rs
@@ -180,6 +180,7 @@ impl DisputeInterface for MockDb {
profile_id: dispute.profile_id,
evidence,
merchant_connector_id: dispute.merchant_connector_id,
+ dispute_amount: dispute.dispute_amount,
};
locked_disputes.push(new_dispute.clone());
@@ -414,6 +415,7 @@ mod tests {
evidence: Some(Secret::from(Value::String("evidence".into()))),
profile_id: None,
merchant_connector_id: None,
+ dispute_amount: 1040,
}
}
diff --git a/migrations/2024-02-28-103308_add_dispute_amount_to_dispute/down.sql b/migrations/2024-02-28-103308_add_dispute_amount_to_dispute/down.sql
new file mode 100644
index 00000000000..e89bb9a356b
--- /dev/null
+++ b/migrations/2024-02-28-103308_add_dispute_amount_to_dispute/down.sql
@@ -0,0 +1,17 @@
+-- This file should undo anything in `up.sql`
+-- Drop the new column
+ALTER TABLE dispute
+DROP COLUMN IF EXISTS dispute_amount;
+
+-- Optionally, if you want to revert the UPDATE statement as well (assuming you have a backup)
+-- You can restore the original data from the backup or use the old values to update the table
+
+-- For example, if you have a backup and want to revert the changes made by the UPDATE statement
+-- You can replace the data with the backup data or the original values
+-- For demonstration purposes, we're assuming you have a backup table named dispute_backup
+
+-- Restore the original values from the backup or any other source
+-- UPDATE dispute
+-- SET dispute_amount = backup.dispute_amount
+-- FROM dispute_backup AS backup
+-- WHERE dispute.id = backup.id;
diff --git a/migrations/2024-02-28-103308_add_dispute_amount_to_dispute/up.sql b/migrations/2024-02-28-103308_add_dispute_amount_to_dispute/up.sql
new file mode 100644
index 00000000000..b56ffc4fe9c
--- /dev/null
+++ b/migrations/2024-02-28-103308_add_dispute_amount_to_dispute/up.sql
@@ -0,0 +1,8 @@
+-- Your SQL goes here
+-- Add the new column with a default value
+ALTER TABLE dispute
+ADD COLUMN dispute_amount BIGINT NOT NULL DEFAULT 0;
+
+-- Update existing rows to set the default value based on the integer equivalent of the amount column
+UPDATE dispute
+SET dispute_amount = CAST(amount AS BIGINT);
|
2024-02-29T08:01:39Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [x] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
adding dispute_amount column as int type because amount in dispute table is of string type on which we cannot have aggregation for analytics
### 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)?
-->run the migration, one column will be added to dispute table called dispute_amount as BIGINT type and will backfill from amount column which is string 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
0936b02ade7f57eaa0213c4f4422bff7c9bb4de2
|
|
juspay/hyperswitch
|
juspay__hyperswitch-3875
|
Bug: [FEATURE] : [NMI] mask pii information in connector request and response
### Feature Description
Mask pii information passed and received in the connector request and response
### Possible Implementation
Refactor all sensitive response and request fields secret
### 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/nmi/transformers.rs b/crates/router/src/connector/nmi/transformers.rs
index 2f8505522b2..efde37d8715 100644
--- a/crates/router/src/connector/nmi/transformers.rs
+++ b/crates/router/src/connector/nmi/transformers.rs
@@ -258,7 +258,7 @@ pub struct NmiCompleteRequest {
transaction_type: TransactionType,
security_key: Secret<String>,
orderid: Option<String>,
- customer_vault_id: String,
+ customer_vault_id: Secret<String>,
email: Option<Email>,
cardholder_auth: Option<String>,
cavv: Option<String>,
@@ -266,8 +266,9 @@ pub struct NmiCompleteRequest {
eci: Option<String>,
cvv: Secret<String>,
three_ds_version: Option<String>,
- directory_server_id: Option<String>,
+ directory_server_id: Option<Secret<String>>,
}
+
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
#[serde(untagged)]
@@ -292,8 +293,8 @@ pub struct NmiRedirectResponseData {
card_holder_auth: Option<String>,
three_ds_version: Option<String>,
order_id: Option<String>,
- directory_server_id: Option<String>,
- customer_vault_id: String,
+ directory_server_id: Option<Secret<String>>,
+ customer_vault_id: Secret<String>,
}
impl TryFrom<&NmiRouterData<&types::PaymentsCompleteAuthorizeRouterData>> for NmiCompleteRequest {
|
2024-02-28T13:27:17Z
|
## 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 -->
Mask pii information passed and received in the connector request and response for NMI.
## Test Case
1. Create a NMI 3ds payment
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_IjTXpFN88jjlzCgq9fDoJQkxPlxCFLrX2YcbkN1XMD29aEuzJK8ew3rtsEfC1Fp6' \
--data-raw '{
"amount": 6540,
"currency": "PLN",
"confirm": true,
"business_country": "US",
"business_label": "default",
"amount_to_capture": 6540,
"capture_method": "automatic",
"customer_id": "AKS1",
"capture_on": "2022-09-10T10:11:12Z",
"authentication_type": "three_ds",
"return_url": "https://hs-payments-test.netlify.app/payments",
"email": "arjun.karthik@juspay.in",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"statement_descriptor_name": "Juspay",
"statement_descriptor_suffix": "Router",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4111111111111111",
"card_exp_month": "12",
"card_exp_year": "2030",
"card_holder_name": "joseph Doe",
"card_cvc": "838"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "CA",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "New York",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"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": "125.0.0.1"
},
"metadata": {
"order_details": {
"product_name": "Apple iphone 15",
"quantity": 1,
"amount": 3200,
"account_name": "transaction_processing"
}
}
}'
```
2. Check if `apple_pay_payment_token` in the `masked_response` is masked
```
curl --location '{{base_url}}/analytics/v1/connector_event_logs?type=Payment&payment_id={{payment_id}}' \
--header 'sec-ch-ua: "Not A(Brand";v="99", "Google Chrome";v="121", "Chromium";v="121"' \
--header 'sec-ch-ua-mobile: ?0' \
--header 'authorization: Bearer JWT_token' \
--header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36' \
--header 'Content-Type: application/json' \
--header 'Referer: https://integ.hyperswitch.io/' \
--header 'api-key: {{api-key}}' \
--header 'sec-ch-ua-platform: "macOS"'
```
Response
```
request\":\"{\\\"security_key\\\":\\\"*** alloc::string::String ***\\\",\\\"ccnumber\\\":\\\"411111**********\\\",\\\"ccexp\\\":\\\"*** alloc::string::String ***\\\",\\\"cvv\\\":\\\"*** alloc::string::String ***\\\",\\\"first_name\\\":\\\"*** alloc::string::String ***\\\",\\\"last_name\\\":\\\"*** alloc::string::String ***\\\",\\\"address1\\\":\\\"*** alloc::string::String ***\\\",\\\"address2\\\":\\\"*** alloc::string::String ***\\\",\\\"city\\\":\\\"San Fransico\\\",\\\"state\\\":\\\"*** alloc::string::String ***\\\",\\\"zip\\\":\\\"*** alloc::string::String ***\\\",\\\"country\\\":\\\"US\\\",\\\"customer_vault\\\":\\\"add_customer\\\"}\",
"masked_response\":\"{\\\"response\\\":\\\"Approved\\\",\\\"responsetext\\\":\\\"Customer Added\\\",\\\"customer_vault_id\\\":\\\"*** alloc::string::String ***\\\",\\\"response_code\\\":\\\"100\\\",\\\"transactionid\\\":\\\"\\\"}
```
## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
44eef46e5d7f0a198be80602ceae1c843449319c
|
|
juspay/hyperswitch
|
juspay__hyperswitch-3914
|
Bug: [FEATURE] statement_descriptor_suffix and statement_descriptor_name not being sent to Adyen. Please implement.
### Feature Description
It is important to be able to have custom statements (and also it is available feature on Stripe), so it should be on Adyen as well.
### Possible Implementation
It should propagate to `shopperStatement` in the Adyen't API
### 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/config/deployments/production.toml b/config/deployments/production.toml
index 382ad018f1d..7c543feed7e 100644
--- a/config/deployments/production.toml
+++ b/config/deployments/production.toml
@@ -17,7 +17,7 @@ payout_connector_list = "wise"
[connectors]
aci.base_url = "https://eu-test.oppwa.com/"
-adyen.base_url = "https://{{merchant_endpoint_prefix}}-checkout-live.adyenpayments.com/"
+adyen.base_url = "https://{{merchant_endpoint_prefix}}-checkout-live.adyenpayments.com/checkout"
adyen.secondary_base_url = "https://{{merchant_endpoint_prefix}}-pal-live.adyenpayments.com/"
airwallex.base_url = "https://api-demo.airwallex.com/"
applepay.base_url = "https://apple-pay-gateway.apple.com/"
diff --git a/config/development.toml b/config/development.toml
index 6d4914af8b4..41497021c3a 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -88,7 +88,7 @@ vault_private_key = ""
tunnel_private_key = ""
[connectors.supported]
-wallets = ["klarna", "braintree", "applepay"]
+wallets = ["klarna", "braintree", "applepay", "adyen"]
rewards = ["cashtocode", "zen"]
cards = [
"aci",
@@ -323,8 +323,8 @@ pay_bright = { country = "CA", currency = "CAD" }
walley = { country = "SE,NO,DK,FI", currency = "DKK,EUR,NOK,SEK" }
giropay = { country = "DE", currency = "EUR" }
eps = { country = "AT", currency = "EUR" }
-sofort = { country = "AT,BE,DE,ES,CH,NL", currency = "CHF,EUR"}
-ideal = { country = "NL", currency = "EUR" }
+sofort = {not_available_flows = { capture_method = "manual" }, country = "AT,BE,DE,ES,CH,NL", currency = "CHF,EUR"}
+ideal = { not_available_flows = { capture_method = "manual" }, country = "NL", currency = "EUR" }
blik = {country = "PL", currency = "PLN"}
trustly = {country = "ES,GB,SE,NO,AT,NL,DE,DK,FI,EE,LT,LV", currency = "CZK,DKK,EUR,GBP,NOK,SEK"}
online_banking_czech_republic = {country = "CZ", currency = "EUR,CZK"}
diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs
index c44d590e2f1..8af99420fa4 100644
--- a/crates/router/src/connector/adyen/transformers.rs
+++ b/crates/router/src/connector/adyen/transformers.rs
@@ -9,12 +9,10 @@ use reqwest::Url;
use serde::{Deserialize, Serialize};
use time::{Duration, OffsetDateTime, PrimitiveDateTime};
-#[cfg(feature = "payouts")]
-use crate::{connector::utils::AddressDetailsData, types::api::payouts, utils::OptionExt};
use crate::{
connector::utils::{
- self, BrowserInformationData, CardData, MandateReferenceData, PaymentsAuthorizeRequestData,
- RouterData,
+ self, AddressDetailsData, BrowserInformationData, CardData, MandateReferenceData,
+ PaymentsAuthorizeRequestData, RouterData,
},
consts,
core::errors,
@@ -29,6 +27,8 @@ use crate::{
},
utils as crate_utils,
};
+#[cfg(feature = "payouts")]
+use crate::{types::api::payouts, utils::OptionExt};
type Error = error_stack::Report<errors::ConnectorError>;
@@ -130,12 +130,12 @@ pub struct ShopperName {
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Address {
- city: Option<String>,
- country: Option<api_enums::CountryAlpha2>,
- house_number_or_name: Option<Secret<String>>,
- postal_code: Option<Secret<String>>,
+ city: String,
+ country: api_enums::CountryAlpha2,
+ house_number_or_name: Secret<String>,
+ postal_code: Secret<String>,
state_or_province: Option<Secret<String>>,
- street: Option<Secret<String>>,
+ street: Secret<String>,
}
#[derive(Debug, Serialize)]
@@ -165,8 +165,11 @@ pub struct AdyenPaymentRequest<'a> {
shopper_reference: Option<String>,
store_payment_method: Option<bool>,
shopper_name: Option<ShopperName>,
+ #[serde(rename = "shopperIP")]
+ shopper_ip: Option<Secret<String, pii::IpAddress>>,
shopper_locale: Option<String>,
shopper_email: Option<Email>,
+ shopper_statement: Option<String>,
social_security_number: Option<Secret<String>>,
telephone_number: Option<Secret<String>>,
billing_address: Option<Address>,
@@ -174,6 +177,7 @@ pub struct AdyenPaymentRequest<'a> {
country_code: Option<api_enums::CountryAlpha2>,
line_items: Option<Vec<LineItem>>,
channel: Option<Channel>,
+ metadata: Option<pii::SecretSerdeValue>,
}
#[derive(Debug, Serialize)]
@@ -1729,16 +1733,22 @@ fn get_amount_data(item: &AdyenRouterData<&types::PaymentsAuthorizeRouterData>)
}
}
-fn get_address_info(address: Option<&api_models::payments::Address>) -> Option<Address> {
+fn get_address_info(
+ address: Option<&api_models::payments::Address>,
+) -> Option<Result<Address, error_stack::Report<errors::ConnectorError>>> {
address.and_then(|add| {
- add.address.as_ref().map(|a| Address {
- city: a.city.clone(),
- country: a.country,
- house_number_or_name: a.line1.clone(),
- postal_code: a.zip.clone(),
- state_or_province: a.state.clone(),
- street: a.line2.clone(),
- })
+ add.address.as_ref().map(
+ |a| -> Result<Address, error_stack::Report<errors::ConnectorError>> {
+ Ok(Address {
+ city: a.get_city()?.to_owned(),
+ country: a.get_country()?.to_owned(),
+ house_number_or_name: a.get_line1()?.to_owned(),
+ postal_code: a.get_zip()?.to_owned(),
+ state_or_province: a.state.clone(),
+ street: a.get_line2()?.to_owned(),
+ })
+ },
+ )
})
}
@@ -1823,6 +1833,12 @@ fn get_social_security_number(
}
}
+fn build_shopper_reference(customer_id: &Option<String>, merchant_id: String) -> Option<String> {
+ customer_id
+ .clone()
+ .map(|c_id| format!("{}_{}", merchant_id, c_id))
+}
+
impl<'a> TryFrom<&api_models::payments::BankDebitData> for AdyenPaymentMethod<'a> {
type Error = Error;
fn try_from(
@@ -2125,27 +2141,81 @@ impl<'a> TryFrom<&api::WalletData> for AdyenPaymentMethod<'a> {
}
}
-impl<'a> TryFrom<(&api::PayLaterData, Option<api_enums::CountryAlpha2>)>
- for AdyenPaymentMethod<'a>
+pub fn check_required_field<'a, T>(
+ field: &'a Option<T>,
+ message: &'static str,
+) -> Result<&'a T, errors::ConnectorError> {
+ field
+ .as_ref()
+ .ok_or(errors::ConnectorError::MissingRequiredField {
+ field_name: message,
+ })
+}
+
+impl<'a>
+ TryFrom<(
+ &api::PayLaterData,
+ &Option<api_enums::CountryAlpha2>,
+ &Option<Email>,
+ &Option<String>,
+ &Option<ShopperName>,
+ &Option<Secret<String>>,
+ &Option<Address>,
+ &Option<Address>,
+ )> for AdyenPaymentMethod<'a>
{
type Error = Error;
fn try_from(
- value: (&api::PayLaterData, Option<api_enums::CountryAlpha2>),
+ value: (
+ &api::PayLaterData,
+ &Option<api_enums::CountryAlpha2>,
+ &Option<Email>,
+ &Option<String>,
+ &Option<ShopperName>,
+ &Option<Secret<String>>,
+ &Option<Address>,
+ &Option<Address>,
+ ),
) -> Result<Self, Self::Error> {
- let (pay_later_data, country_code) = value;
+ let (
+ pay_later_data,
+ country_code,
+ shopper_email,
+ shopper_reference,
+ shopper_name,
+ telephone_number,
+ billing_address,
+ delivery_address,
+ ) = value;
match pay_later_data {
api_models::payments::PayLaterData::KlarnaRedirect { .. } => {
let klarna = PmdForPaymentType {
payment_type: PaymentType::Klarna,
};
+ check_required_field(shopper_email, "email")?;
+ check_required_field(shopper_reference, "customer_id")?;
+ check_required_field(country_code, "billing.country")?;
+
Ok(AdyenPaymentMethod::AdyenKlarna(Box::new(klarna)))
}
- api_models::payments::PayLaterData::AffirmRedirect { .. } => Ok(
- AdyenPaymentMethod::AdyenAffirm(Box::new(PmdForPaymentType {
- payment_type: PaymentType::Affirm,
- })),
- ),
+ api_models::payments::PayLaterData::AffirmRedirect { .. } => {
+ check_required_field(shopper_email, "email")?;
+ check_required_field(shopper_name, "billing.first_name, billing.last_name")?;
+ check_required_field(telephone_number, "billing.phone")?;
+ check_required_field(billing_address, "billing")?;
+
+ Ok(AdyenPaymentMethod::AdyenAffirm(Box::new(
+ PmdForPaymentType {
+ payment_type: PaymentType::Affirm,
+ },
+ )))
+ }
api_models::payments::PayLaterData::AfterpayClearpayRedirect { .. } => {
+ check_required_field(shopper_email, "email")?;
+ check_required_field(shopper_name, "billing.first_name, billing.last_name")?;
+ check_required_field(delivery_address, "shipping")?;
+ check_required_field(billing_address, "billing")?;
+
if let Some(country) = country_code {
match country {
api_enums::CountryAlpha2::IT
@@ -2163,17 +2233,36 @@ impl<'a> TryFrom<(&api::PayLaterData, Option<api_enums::CountryAlpha2>)>
}
}
api_models::payments::PayLaterData::PayBrightRedirect { .. } => {
+ check_required_field(shopper_name, "billing.first_name, billing.last_name")?;
+ check_required_field(telephone_number, "billing.phone")?;
+ check_required_field(shopper_email, "email")?;
+ check_required_field(billing_address, "billing")?;
+ check_required_field(delivery_address, "shipping")?;
+ check_required_field(country_code, "billing.country")?;
Ok(AdyenPaymentMethod::PayBright)
}
api_models::payments::PayLaterData::WalleyRedirect { .. } => {
+ //[TODO: Line items specific sub-fields are mandatory]
+ check_required_field(telephone_number, "billing.phone")?;
+ check_required_field(shopper_email, "email")?;
Ok(AdyenPaymentMethod::Walley)
}
- api_models::payments::PayLaterData::AlmaRedirect { .. } => Ok(
- AdyenPaymentMethod::AlmaPayLater(Box::new(PmdForPaymentType {
- payment_type: PaymentType::Alma,
- })),
- ),
+ api_models::payments::PayLaterData::AlmaRedirect { .. } => {
+ check_required_field(telephone_number, "billing.phone")?;
+ check_required_field(shopper_email, "email")?;
+ check_required_field(billing_address, "billing")?;
+ check_required_field(delivery_address, "shipping")?;
+ Ok(AdyenPaymentMethod::AlmaPayLater(Box::new(
+ PmdForPaymentType {
+ payment_type: PaymentType::Alma,
+ },
+ )))
+ }
api_models::payments::PayLaterData::AtomeRedirect { .. } => {
+ check_required_field(shopper_email, "email")?;
+ check_required_field(shopper_name, "billing.first_name, billing.last_name")?;
+ check_required_field(telephone_number, "billing.phone")?;
+ check_required_field(billing_address, "billing")?;
Ok(AdyenPaymentMethod::Atome)
}
payments::PayLaterData::KlarnaSdk { .. } => Err(errors::ConnectorError::NotSupported {
@@ -2544,6 +2633,9 @@ impl<'a>
shopper_reference,
store_payment_method,
channel: None,
+ shopper_statement: item.router_data.request.statement_descriptor.clone(),
+ shopper_ip: item.router_data.request.get_ip_address_as_optional(),
+ metadata: item.router_data.request.metadata.clone(),
})
}
}
@@ -2564,12 +2656,22 @@ impl<'a>
let amount = get_amount_data(item);
let auth_type = AdyenAuthType::try_from(&item.router_data.connector_auth_type)?;
let shopper_interaction = AdyenShopperInteraction::from(item.router_data);
- let (recurring_processing_model, store_payment_method, shopper_reference) =
+ let shopper_reference = build_shopper_reference(
+ &item.router_data.customer_id,
+ item.router_data.merchant_id.clone(),
+ );
+ let (recurring_processing_model, store_payment_method, _) =
get_recurring_processing_model(item.router_data)?;
let browser_info = get_browser_info(item.router_data)?;
+ let billing_address =
+ get_address_info(item.router_data.address.billing.as_ref()).transpose()?;
+ let country_code = get_country_code(item.router_data.address.billing.as_ref());
let additional_data = get_additional_data(item.router_data);
let return_url = item.router_data.request.get_return_url()?;
let payment_method = AdyenPaymentMethod::try_from(card_data)?;
+ let shopper_email = item.router_data.request.email.clone();
+ let shopper_name = get_shopper_name(item.router_data.address.billing.as_ref());
+
Ok(AdyenPaymentRequest {
amount,
merchant_account: auth_type.merchant_account,
@@ -2581,17 +2683,20 @@ impl<'a>
browser_info,
additional_data,
telephone_number: None,
- shopper_name: None,
- shopper_email: None,
+ shopper_name,
+ shopper_email,
shopper_locale: None,
social_security_number: None,
- billing_address: None,
+ billing_address,
delivery_address: None,
- country_code: None,
+ country_code,
line_items: None,
shopper_reference,
store_payment_method,
channel: None,
+ shopper_statement: item.router_data.request.statement_descriptor.clone(),
+ shopper_ip: item.router_data.request.get_ip_address_as_optional(),
+ metadata: item.router_data.request.metadata.clone(),
})
}
}
@@ -2642,6 +2747,9 @@ impl<'a>
shopper_reference: None,
store_payment_method: None,
channel: None,
+ shopper_statement: item.router_data.request.statement_descriptor.clone(),
+ shopper_ip: item.router_data.request.get_ip_address_as_optional(),
+ metadata: item.router_data.request.metadata.clone(),
};
Ok(request)
}
@@ -2693,6 +2801,9 @@ impl<'a>
shopper_reference: None,
store_payment_method: None,
channel: None,
+ shopper_statement: item.router_data.request.statement_descriptor.clone(),
+ shopper_ip: item.router_data.request.get_ip_address_as_optional(),
+ metadata: item.router_data.request.metadata.clone(),
};
Ok(request)
}
@@ -2740,6 +2851,9 @@ impl<'a>
shopper_reference: None,
store_payment_method: None,
channel: None,
+ shopper_statement: item.router_data.request.statement_descriptor.clone(),
+ shopper_ip: item.router_data.request.get_ip_address_as_optional(),
+ metadata: item.router_data.request.metadata.clone(),
};
Ok(request)
}
@@ -2787,6 +2901,9 @@ impl<'a>
store_payment_method: None,
channel: None,
social_security_number: None,
+ shopper_statement: item.router_data.request.statement_descriptor.clone(),
+ shopper_ip: item.router_data.request.get_ip_address_as_optional(),
+ metadata: item.router_data.request.metadata.clone(),
};
Ok(request)
}
@@ -2841,6 +2958,9 @@ impl<'a>
shopper_reference,
store_payment_method,
channel: None,
+ shopper_statement: item.router_data.request.statement_descriptor.clone(),
+ shopper_ip: item.router_data.request.get_ip_address_as_optional(),
+ metadata: item.router_data.request.metadata.clone(),
})
}
}
@@ -2935,6 +3055,9 @@ impl<'a>
shopper_reference,
store_payment_method,
channel,
+ shopper_statement: item.router_data.request.statement_descriptor.clone(),
+ shopper_ip: item.router_data.request.get_ip_address_as_optional(),
+ metadata: item.router_data.request.metadata.clone(),
})
}
}
@@ -2958,18 +3081,33 @@ impl<'a>
let browser_info = get_browser_info(item.router_data)?;
let additional_data = get_additional_data(item.router_data);
let country_code = get_country_code(item.router_data.address.billing.as_ref());
- let payment_method = AdyenPaymentMethod::try_from((paylater_data, country_code))?;
let shopper_interaction = AdyenShopperInteraction::from(item.router_data);
- let (recurring_processing_model, store_payment_method, shopper_reference) =
+ let shopper_reference = build_shopper_reference(
+ &item.router_data.customer_id,
+ item.router_data.merchant_id.clone(),
+ );
+ let (recurring_processing_model, store_payment_method, _) =
get_recurring_processing_model(item.router_data)?;
let return_url = item.router_data.request.get_return_url()?;
let shopper_name: Option<ShopperName> =
get_shopper_name(item.router_data.address.billing.as_ref());
let shopper_email = item.router_data.request.email.clone();
- let billing_address = get_address_info(item.router_data.address.billing.as_ref());
- let delivery_address = get_address_info(item.router_data.address.shipping.as_ref());
+ let billing_address =
+ get_address_info(item.router_data.address.billing.as_ref()).transpose()?;
+ let delivery_address =
+ get_address_info(item.router_data.address.shipping.as_ref()).transpose()?;
let line_items = Some(get_line_items(item));
let telephone_number = get_telephone_number(item.router_data);
+ let payment_method = AdyenPaymentMethod::try_from((
+ paylater_data,
+ &country_code,
+ &shopper_email,
+ &shopper_reference,
+ &shopper_name,
+ &telephone_number,
+ &billing_address,
+ &delivery_address,
+ ))?;
Ok(AdyenPaymentRequest {
amount,
merchant_account: auth_type.merchant_account,
@@ -2992,6 +3130,9 @@ impl<'a>
shopper_reference,
store_payment_method,
channel: None,
+ shopper_statement: item.router_data.request.statement_descriptor.clone(),
+ shopper_ip: item.router_data.request.get_ip_address_as_optional(),
+ metadata: item.router_data.request.metadata.clone(),
})
}
}
@@ -3047,6 +3188,9 @@ impl<'a>
store_payment_method: None,
channel: None,
social_security_number: None,
+ shopper_statement: item.router_data.request.statement_descriptor.clone(),
+ shopper_ip: item.router_data.request.get_ip_address_as_optional(),
+ metadata: item.router_data.request.metadata.clone(),
})
}
}
@@ -4522,7 +4666,8 @@ impl<F> TryFrom<&AdyenRouterData<&types::PayoutsRouterData<F>>> for AdyenPayoutC
date_of_birth: None,
entity_type: Some(item.router_data.request.entity_type),
nationality: get_country_code(item.router_data.address.billing.as_ref()),
- billing_address: get_address_info(item.router_data.address.billing.as_ref()),
+ billing_address: get_address_info(item.router_data.address.billing.as_ref())
+ .transpose()?,
})
}
PayoutMethodData::Wallet(wallet_data) => {
@@ -4561,7 +4706,8 @@ impl<F> TryFrom<&AdyenRouterData<&types::PayoutsRouterData<F>>> for AdyenPayoutC
date_of_birth: None,
entity_type: Some(item.router_data.request.entity_type),
nationality: get_country_code(item.router_data.address.billing.as_ref()),
- billing_address: get_address_info(item.router_data.address.billing.as_ref()),
+ billing_address: get_address_info(item.router_data.address.billing.as_ref())
+ .transpose()?,
})
}
}
@@ -4598,7 +4744,8 @@ impl<F> TryFrom<&AdyenRouterData<&types::PayoutsRouterData<F>>> for AdyenPayoutF
currency: item.router_data.request.destination_currency,
},
card: PayoutCardDetails::try_from(&item.router_data.get_payout_method_data()?)?,
- billing_address: get_address_info(item.router_data.get_billing().ok()),
+ billing_address: get_address_info(item.router_data.get_billing().ok())
+ .transpose()?,
merchant_account,
reference: item.router_data.request.payout_id.clone(),
shopper_name: ShopperName {
|
2024-03-07T12:25:27Z
|
## 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 -->
- Add shopper statement and metadata in payments request
- Add additional fields and validations over fields like `IP address`, `billing_address`, `Email` and Shopper details
### 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`
-->
Production URL got updated for Adyen
## 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).
-->
#3914
## 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 Klarna Payment
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_6LLuoNT8iBk4hTwVLSQ6zTJOiBmeuLSJ5NoakZTZItC4IifnHLy7cTWPZXW4uhbq' \
--data-raw '{
"amount": 6540,
"currency": "EUR",
"confirm": true,
"capture_method": "manual",
"capture_on": "2022-09-10T10:11:12Z",
"amount_to_capture": 6540,
"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",
"profile_id": "pro_B0AWG00VLGTFt4rTrj6a",
"business_country": "US",
"payment_method": "pay_later",
"payment_method_type": "klarna",
"payment_experience": "redirect_to_url",
"connector": [
"adyen"
],
"payment_method_data": {
"pay_later": {
"klarna_redirect": {
"billing_email": "hyperswitch_sdk_demo_id@gmail.com",
"billing_country": "DE"
}
}
},
"routing": {
"type": "single",
"data": "adyen"
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "DE",
"first_name": "PiX"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "PiX"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}'
```
- Test in Adyen dashboard all the fields should be visible like shopper statement, address and shopper reference
- Klarna Validation when not sending Email
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_6LLuoNT8iBk4hTwVLSQ6zTJOiBmeuLSJ5NoakZTZItC4IifnHLy7cTWPZXW4uhbq' \
--data-raw '{
"amount": 6540,
"currency": "EUR",
"confirm": true,
"capture_method": "manual",
"capture_on": "2022-09-10T10:11:12Z",
"amount_to_capture": 6540,
"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",
"profile_id": "pro_B0AWG00VLGTFt4rTrj6a",
"business_country": "US",
"payment_method": "pay_later",
"payment_method_type": "klarna",
"payment_experience": "redirect_to_url",
"connector": [
"adyen"
],
"payment_method_data": {
"pay_later": {
"klarna_redirect": {
"billing_email": "hyperswitch_sdk_demo_id@gmail.com",
"billing_country": "DE"
}
}
},
"routing": {
"type": "single",
"data": "adyen"
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "DE",
"first_name": "PiX"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "PiX"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
}
}'
```
Expected Response:
```
{
"error": {
"type": "invalid_request",
"message": "Missing required param: email",
"code": "IR_04"
}
}
```
## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
7391416e2473eab0474bd01bb155a9ecc96da263
|
|
juspay/hyperswitch
|
juspay__hyperswitch-3873
|
Bug: FEATURE] : [Nexinets] mask pii information in connector request and response
### Feature Description
Mask pii information passed and received in the connector request and response
### Possible Implementation
Refactor all sensitive response and request fields secret
### 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/nexinets/transformers.rs b/crates/router/src/connector/nexinets/transformers.rs
index 07488271aea..9fdaaa36b36 100644
--- a/crates/router/src/connector/nexinets/transformers.rs
+++ b/crates/router/src/connector/nexinets/transformers.rs
@@ -3,7 +3,7 @@ use base64::Engine;
use cards::CardNumber;
use common_utils::errors::CustomResult;
use error_stack::{IntoReport, ResultExt};
-use masking::{PeekInterface, Secret};
+use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use url::Url;
@@ -86,7 +86,7 @@ pub struct CardDetails {
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentInstrument {
- payment_instrument_id: Option<String>,
+ payment_instrument_id: Option<Secret<String>>,
}
#[derive(Debug, Serialize)]
@@ -357,7 +357,7 @@ impl<F, T>
.payment_instrument
.payment_instrument_id
.map(|id| types::MandateReference {
- connector_mandate_id: Some(id),
+ connector_mandate_id: Some(id.expose()),
payment_method_id: None,
});
Ok(Self {
@@ -641,7 +641,7 @@ fn get_card_data(
true => {
let card_data = match item.request.off_session {
Some(true) => CardDataDetails::PaymentInstrument(Box::new(PaymentInstrument {
- payment_instrument_id: item.request.connector_mandate_id(),
+ payment_instrument_id: item.request.connector_mandate_id().map(Secret::new),
})),
_ => CardDataDetails::CardDetails(Box::new(get_card_details(card)?)),
};
|
2024-02-28T12:17:11Z
|
## 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 -->
Mask pii information passed and received in the connector request and response for Nexinets.
## Test Case
<!--
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 mandate payment
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key:{{api_key}}' \
--data-raw '{
"amount": 6540,
"currency": "EUR",
"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": "+65",
"description": "Its my first payment request",
"authentication_type": "no_three_ds",
"return_url": "https://duck.com",
"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"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "PiX"
}
},
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "PiX"
}
},
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "value1",
"new_customer": "true",
"login_date": "2019-09-10T10:11:12Z"
},
"setup_future_usage": "off_session",
"mandate_data": {
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "13.232.74.226",
"user_agent": "amet irure esse"
}
},
"mandate_type": {
"multi_use": {
"amount": 799,
"currency": "USD"
}
}
}
}'
```
1.b. Check if all the sensitive data in the `masked_response` and also in `request` is masked
```
curl --location '{{base_url}}/analytics/v1/connector_event_logs?type=Payment&payment_id={{payment_id}}' \
--header 'sec-ch-ua: "Not A(Brand";v="99", "Google Chrome";v="121", "Chromium";v="121"' \
--header 'sec-ch-ua-mobile: ?0' \
--header 'authorization: Bearer JWT_token' \
--header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36' \
--header 'Content-Type: application/json' \
--header 'Referer: https://integ.hyperswitch.io/' \
--header 'api-key: {{api-key}}' \
--header 'sec-ch-ua-platform: "macOS"'
```
Response:
```
masked_response\ : {\\\"orderId\\\":\\\"qyompda9ts\\\",\\\"transactionType\\\":\\\"DEBIT\\\",\\\"transactions\\\":[{\\\"transactionId\\\":\\\"transaction_bsglkkgnm3\\\",\\\"type\\\":\\\"DEBIT\\\",\\\"currency\\\":\\\"EUR\\\",\\\"status\\\":\\\"PENDING\\\"}],\\\"paymentInstrument\\\":{\\\"paymentInstrumentId\\\":\\\"*** alloc::string::String ***\\\"}
```
_Note:MIT is not fully implemented in Nexinets_
## Impact Area
1. CIT Payment create
## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
d220e815dc81925b205fb57d5d4f05883c1a7cde
|
|
juspay/hyperswitch
|
juspay__hyperswitch-3891
|
Bug: Generate and publish Open API specs
|
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 33d355d255a..dd0c5e4b05c 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -354,6 +354,7 @@ pub struct PaymentsRequest {
pub mandate_data: Option<MandateData>,
/// Passing this object during payments confirm . The customer_acceptance sub object is usually passed by the SDK or client
+ #[schema(value_type = Option<CustomerAcceptance>)]
pub customer_acceptance: Option<CustomerAcceptance>,
/// A unique identifier to link the payment to a mandate. To do Recurring payments after a mandate has been created, pass the mandate_id instead of payment_method_data
diff --git a/crates/openapi/src/routes/customers.rs b/crates/openapi/src/routes/customers.rs
index 6011621fc13..6a6f41d98cd 100644
--- a/crates/openapi/src/routes/customers.rs
+++ b/crates/openapi/src/routes/customers.rs
@@ -124,7 +124,8 @@ pub async fn customers_mandates_list() {}
get,
path = "/{customer_id}/payment_methods/{payment_method_id}/default",
params (
- ("method_id" = String, Path, description = "Set the Payment Method as Default for the Customer"),
+ ("customer_id" = String,Path, description ="The unique identifier for the Customer"),
+ ("payment_method_id" = String,Path, description = "The unique identifier for the Payment Method"),
),
responses(
(status = 200, description = "Payment Method has been set as default", body =CustomerDefaultPaymentMethodResponse ),
diff --git a/crates/openapi/src/routes/payments.rs b/crates/openapi/src/routes/payments.rs
index 12fc7778a31..20d87b91e79 100644
--- a/crates/openapi/src/routes/payments.rs
+++ b/crates/openapi/src/routes/payments.rs
@@ -100,6 +100,14 @@
"currency": "USD"
}
}
+ },
+ "customer_acceptance": {
+ "acceptance_type": "offline",
+ "accepted_at": "1963-05-03T04:07:52.723Z",
+ "online": {
+ "ip_address": "127.0.0.1",
+ "user_agent": "amet irure esse"
+ }
}
})
)
@@ -302,6 +310,14 @@ pub fn payments_update() {}
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
+ },
+ "customer_acceptance": {
+ "acceptance_type": "offline",
+ "accepted_at": "1963-05-03T04:07:52.723Z",
+ "online": {
+ "ip_address": "127.0.0.1",
+ "user_agent": "amet irure esse"
+ }
}
}
)
diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json
index 66007b69342..940218acf31 100644
--- a/openapi/openapi_spec.json
+++ b/openapi/openapi_spec.json
@@ -2606,6 +2606,14 @@
"authentication_type": "no_three_ds",
"confirm": true,
"currency": "USD",
+ "customer_acceptance": {
+ "acceptance_type": "offline",
+ "accepted_at": "1963-05-03T04:07:52.723Z",
+ "online": {
+ "ip_address": "127.0.0.1",
+ "user_agent": "amet irure esse"
+ }
+ },
"customer_id": "StripeCustomer123",
"mandate_data": {
"customer_acceptance": {
@@ -3153,6 +3161,14 @@
"examples": {
"Confirm a payment with payment method data": {
"value": {
+ "customer_acceptance": {
+ "acceptance_type": "offline",
+ "accepted_at": "1963-05-03T04:07:52.723Z",
+ "online": {
+ "ip_address": "127.0.0.1",
+ "user_agent": "amet irure esse"
+ }
+ },
"payment_method": "card",
"payment_method_data": {
"card": {
@@ -4208,9 +4224,18 @@
"operationId": "Set the Payment Method as Default",
"parameters": [
{
- "name": "method_id",
+ "name": "customer_id",
"in": "path",
- "description": "Set the Payment Method as Default for the Customer",
+ "description": "The unique identifier for the Customer",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ },
+ {
+ "name": "payment_method_id",
+ "in": "path",
+ "description": "The unique identifier for the Payment Method",
"required": true,
"schema": {
"type": "string"
|
2024-03-12T09:57:46Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
update open-api spec to have payment 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)?
-->
## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
ac8ddd40208f3da5f65ca97bf5033cea5ca3ebe3
|
|
juspay/hyperswitch
|
juspay__hyperswitch-3871
|
Bug: feat: add groups for get_role_from_token api
|
diff --git a/crates/api_models/src/events/user_role.rs b/crates/api_models/src/events/user_role.rs
index f46c5cf312b..aee2b3fb66c 100644
--- a/crates/api_models/src/events/user_role.rs
+++ b/crates/api_models/src/events/user_role.rs
@@ -2,8 +2,8 @@ use common_utils::events::{ApiEventMetric, ApiEventsType};
use crate::user_role::{
role::{
- CreateRoleRequest, GetRoleRequest, ListRolesResponse, RoleInfoResponse,
- RoleInfoWithPermissionsResponse, UpdateRoleRequest,
+ CreateRoleRequest, GetRoleFromTokenResponse, GetRoleRequest, ListRolesResponse,
+ RoleInfoResponse, RoleInfoWithPermissionsResponse, UpdateRoleRequest,
},
AcceptInvitationRequest, AuthorizationInfoResponse, DeleteUserRoleRequest,
TransferOrgOwnershipRequest, UpdateUserRoleRequest,
@@ -20,5 +20,6 @@ common_utils::impl_misc_api_event_type!(
CreateRoleRequest,
UpdateRoleRequest,
ListRolesResponse,
- RoleInfoResponse
+ RoleInfoResponse,
+ GetRoleFromTokenResponse
);
diff --git a/crates/api_models/src/user_role/role.rs b/crates/api_models/src/user_role/role.rs
index fafb8fede0b..6d0bb2154d9 100644
--- a/crates/api_models/src/user_role/role.rs
+++ b/crates/api_models/src/user_role/role.rs
@@ -23,6 +23,13 @@ pub struct GetGroupsQueryParam {
pub groups: Option<bool>,
}
+#[derive(Debug, serde::Serialize)]
+#[serde(untagged)]
+pub enum GetRoleFromTokenResponse {
+ Permissions(Vec<Permission>),
+ Groups(Vec<PermissionGroup>),
+}
+
#[derive(Debug, serde::Serialize)]
#[serde(untagged)]
pub enum RoleInfoResponse {
diff --git a/crates/router/src/core/user_role/role.rs b/crates/router/src/core/user_role/role.rs
index cc31798bd8b..c3d534f8860 100644
--- a/crates/router/src/core/user_role/role.rs
+++ b/crates/router/src/core/user_role/role.rs
@@ -1,7 +1,4 @@
-use api_models::user_role::{
- role::{self as role_api},
- Permission,
-};
+use api_models::user_role::role::{self as role_api};
use common_enums::RoleScope;
use common_utils::generate_id_with_default_len;
use diesel_models::role::{RoleNew, RoleUpdate};
@@ -20,10 +17,10 @@ use crate::{
utils,
};
-pub async fn get_role_from_token(
+pub async fn get_role_from_token_with_permissions(
state: AppState,
user_from_token: UserFromToken,
-) -> UserResponse<Vec<Permission>> {
+) -> UserResponse<role_api::GetRoleFromTokenResponse> {
let role_info = user_from_token
.get_role_info_from_db(&state)
.await
@@ -35,7 +32,25 @@ pub async fn get_role_from_token(
.map(Into::into)
.collect();
- Ok(ApplicationResponse::Json(permissions))
+ Ok(ApplicationResponse::Json(
+ role_api::GetRoleFromTokenResponse::Permissions(permissions),
+ ))
+}
+
+pub async fn get_role_from_token_with_groups(
+ state: AppState,
+ user_from_token: UserFromToken,
+) -> UserResponse<role_api::GetRoleFromTokenResponse> {
+ let role_info = user_from_token
+ .get_role_info_from_db(&state)
+ .await
+ .attach_printable("Invalid role_id in JWT")?;
+
+ let permissions = role_info.get_permission_groups().to_vec();
+
+ Ok(ApplicationResponse::Json(
+ role_api::GetRoleFromTokenResponse::Groups(permissions),
+ ))
}
pub async fn create_role(
diff --git a/crates/router/src/routes/user_role.rs b/crates/router/src/routes/user_role.rs
index 75de9e7e6f7..65e2aa4cdb8 100644
--- a/crates/router/src/routes/user_role.rs
+++ b/crates/router/src/routes/user_role.rs
@@ -41,14 +41,27 @@ pub async fn get_authorization_info(
.await
}
-pub async fn get_role_from_token(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse {
+pub async fn get_role_from_token(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ query: web::Query<role_api::GetGroupsQueryParam>,
+) -> HttpResponse {
let flow = Flow::GetRoleFromToken;
+ let respond_with_groups = query.into_inner().groups.unwrap_or(false);
+
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
(),
- |state, user, _| role_core::get_role_from_token(state, user),
+ |state, user, _| async move {
+ // TODO: Permissions to be deprecated once groups are stable
+ if respond_with_groups {
+ role_core::get_role_from_token_with_groups(state, user).await
+ } else {
+ role_core::get_role_from_token_with_permissions(state, user).await
+ }
+ },
&auth::DashboardNoPermissionAuth,
api_locking::LockAction::NotApplicable,
))
|
2024-02-28T12:10:44Z
|
## 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 -->
Get role from token will respond with groups if asked.
### 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 #3871
## 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 following api will take a query param called `groups` and if it is set to `true` it will respond with array of groups.
This api was already present previously but was responding with permissions. The default behaviour without the `groups` query param is still the same (permissions will be returned). Groups will only be returned when `groups` param is set to true.
```
curl --location 'http://localhost:8080/user/role?groups=true' \
--header 'Authorization: Bearer JWT'
```
```
[
"users_view"
]
```
## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
f3931cf484f61a4d9c107c362d0f3f6ee872e0e7
|
|
juspay/hyperswitch
|
juspay__hyperswitch-3870
|
Bug: [FEATURE] : [Bitpay] mask pii information in connector request and response
### Feature Description
Mask pii information passed and received in the connector request and response
### Possible Implementation
Refactor all sensitive response and request fields secret
### 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/bitpay/transformers.rs b/crates/router/src/connector/bitpay/transformers.rs
index 148a5a45636..74fa0b5c595 100644
--- a/crates/router/src/connector/bitpay/transformers.rs
+++ b/crates/router/src/connector/bitpay/transformers.rs
@@ -140,8 +140,8 @@ pub struct BitpayPaymentResponseData {
pub exception_status: ExceptionStatus,
pub redirect_url: Option<String>,
pub refund_address_request_pending: Option<bool>,
- pub merchant_name: Option<String>,
- pub token: Option<String>,
+ pub merchant_name: Option<Secret<String>>,
+ pub token: Option<Secret<String>>,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
|
2024-02-19T13:20:26Z
|
## 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 -->
Mask pii information passed and received in the connector request and response for Bitpay
## Test Case
Check if sensitive fields within connector request and response is masked in the click house for Bitpay
Sanity test
1. Payment create - card
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: {{api_key}}' \
--data-raw '{
"amount": 2000,
"currency": "GBP",
"confirm": true,
"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": "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"
}
},
"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"
},
"payment_method": "card",
"payment_method_data": {
"card": {
"card_number": "5123456789012346",
"card_exp_month": "10",
"card_exp_year": "30",
"card_holder_name": "Joseph Doe",
"card_cvc": "123"
}
}
}'
```
response
```
BitpayPaymentsResponse { data: BitpayPaymentResponseData { url: Some(Url { scheme: "https", cannot_be_a_base: false, username: "", password: None, host: Some(Domain("test.bitpay.com")), port: None, path: "/invoice", query: Some("id=8wNbxWa97mrqBCavAQBmi8"), fragment: None }), status: New, price: 2000, currency: "GBP", amount_paid: 0, invoice_time: Some(1708434493106), rate_refresh_time: Some(1708434493106), expiration_time: Some(1708435393106), current_time: Some(1708434493513), id: "8wNbxWa97mrqBCavAQBmi8", order_id: Some("pay_uE8IRzN7s2e3s4AYLq9N_1"), low_fee_detected: Some(false), display_amount_paid: Some("0"), exception_status: Bool(false), redirect_url: None, refund_address_request_pending: Some(false), merchant_name: Some(*** alloc::string::String ***), token: Some(*** alloc::string::String ***) }, facade: Some("pos/invoice") }
```
In logs check for
`topic = "hyperswitch-outgoing-connector-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`
- [x] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
76ac1a753a08f3ecc8ee264e4bccc47e8b219d1d
|
|
juspay/hyperswitch
|
juspay__hyperswitch-3890
|
Bug: Routing changes to choose between MIT details and raw card
Will have to be extended in future to choose between MIT details vs Network Reference ID as well
|
diff --git a/config/development.toml b/config/development.toml
index 6d4914af8b4..6e27e110ee9 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -581,4 +581,4 @@ enabled = true
file_storage_backend = "file_system"
[unmasked_headers]
-keys = "user-agent"
\ No newline at end of file
+keys = "user-agent"
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 6f97a87fbe9..33d355d255a 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -740,7 +740,7 @@ pub enum MandateTransactionType {
#[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)]
pub struct MandateIds {
- pub mandate_id: String,
+ pub mandate_id: Option<String>,
pub mandate_reference_id: Option<MandateReferenceId>,
}
@@ -767,7 +767,7 @@ pub struct UpdateHistory {
impl MandateIds {
pub fn new(mandate_id: String) -> Self {
Self {
- mandate_id,
+ mandate_id: Some(mandate_id),
mandate_reference_id: None,
}
}
diff --git a/crates/router/src/connector/dlocal/transformers.rs b/crates/router/src/connector/dlocal/transformers.rs
index 5eb682d4cfa..c1b8731ee89 100644
--- a/crates/router/src/connector/dlocal/transformers.rs
+++ b/crates/router/src/connector/dlocal/transformers.rs
@@ -139,7 +139,7 @@ impl TryFrom<&DlocalRouterData<&types::PaymentsAuthorizeRouterData>> for DlocalP
.request
.mandate_id
.as_ref()
- .map(|ids| ids.mandate_id.clone()),
+ .and_then(|ids| ids.mandate_id.clone()),
// [#595[FEATURE] Pass Mandate history information in payment flows/request]
installments: item
.router_data
diff --git a/crates/router/src/core/mandate.rs b/crates/router/src/core/mandate.rs
index d07a8814c88..2838edfbf91 100644
--- a/crates/router/src/core/mandate.rs
+++ b/crates/router/src/core/mandate.rs
@@ -326,48 +326,52 @@ where
Err(_) => {}
Ok(_) => match resp.request.get_mandate_id() {
Some(mandate_id) => {
- let mandate_id = &mandate_id.mandate_id;
- let mandate = state
- .store
- .find_mandate_by_merchant_id_mandate_id(resp.merchant_id.as_ref(), mandate_id)
- .await
- .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?;
- let mandate = match mandate.mandate_type {
- storage_enums::MandateType::SingleUse => state
+ if let Some(ref mandate_id) = mandate_id.mandate_id {
+ let mandate = state
.store
- .update_mandate_by_merchant_id_mandate_id(
- &resp.merchant_id,
+ .find_mandate_by_merchant_id_mandate_id(
+ resp.merchant_id.as_ref(),
mandate_id,
- storage::MandateUpdate::StatusUpdate {
- mandate_status: storage_enums::MandateStatus::Revoked,
- },
)
.await
- .change_context(errors::ApiErrorResponse::MandateUpdateFailed),
- storage_enums::MandateType::MultiUse => state
- .store
- .update_mandate_by_merchant_id_mandate_id(
- &resp.merchant_id,
- mandate_id,
- storage::MandateUpdate::CaptureAmountUpdate {
- amount_captured: Some(
- mandate.amount_captured.unwrap_or(0)
- + resp.request.get_amount(),
- ),
- },
- )
- .await
- .change_context(errors::ApiErrorResponse::MandateUpdateFailed),
- }?;
- metrics::SUBSEQUENT_MANDATE_PAYMENT.add(
- &metrics::CONTEXT,
- 1,
- &[metrics::request::add_attributes(
- "connector",
- mandate.connector,
- )],
- );
- resp.payment_method_id = Some(mandate.payment_method_id);
+ .to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?;
+ let mandate = match mandate.mandate_type {
+ storage_enums::MandateType::SingleUse => state
+ .store
+ .update_mandate_by_merchant_id_mandate_id(
+ &resp.merchant_id,
+ mandate_id,
+ storage::MandateUpdate::StatusUpdate {
+ mandate_status: storage_enums::MandateStatus::Revoked,
+ },
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::MandateUpdateFailed),
+ storage_enums::MandateType::MultiUse => state
+ .store
+ .update_mandate_by_merchant_id_mandate_id(
+ &resp.merchant_id,
+ mandate_id,
+ storage::MandateUpdate::CaptureAmountUpdate {
+ amount_captured: Some(
+ mandate.amount_captured.unwrap_or(0)
+ + resp.request.get_amount(),
+ ),
+ },
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::MandateUpdateFailed),
+ }?;
+ metrics::SUBSEQUENT_MANDATE_PAYMENT.add(
+ &metrics::CONTEXT,
+ 1,
+ &[metrics::request::add_attributes(
+ "connector",
+ mandate.connector,
+ )],
+ );
+ resp.payment_method_id = Some(mandate.payment_method_id);
+ }
}
None => {
if resp.request.get_setup_mandate_details().is_some() {
@@ -409,7 +413,7 @@ where
logger::debug!("{:?}", new_mandate_data);
resp.request
.set_mandate_id(Some(api_models::payments::MandateIds {
- mandate_id: new_mandate_data.mandate_id.clone(),
+ mandate_id: Some(new_mandate_data.mandate_id.clone()),
mandate_reference_id: new_mandate_data
.connector_mandate_ids
.clone()
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index ca3bbfd0651..2544bffda72 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -13,7 +13,10 @@ pub mod types;
use std::{fmt::Debug, marker::PhantomData, ops::Deref, time::Instant, vec::IntoIter};
-use api_models::{self, enums, payments::HeaderPayload};
+use api_models::{
+ self, enums,
+ payments::{self as payments_api, HeaderPayload},
+};
use common_utils::{ext_traits::AsyncExt, pii, types::Surcharge};
use data_models::mandates::{CustomerAcceptance, MandateData};
use diesel_models::{ephemeral_key, fraud_check::FraudCheck};
@@ -2061,9 +2064,11 @@ where
pub customer_acceptance: Option<CustomerAcceptance>,
pub address: PaymentAddress,
pub token: Option<String>,
+ pub token_data: Option<storage::PaymentTokenData>,
pub confirm: Option<bool>,
pub force_sync: Option<bool>,
pub payment_method_data: Option<api::PaymentMethodData>,
+ pub payment_method_info: Option<storage::PaymentMethod>,
pub refunds: Vec<storage::Refund>,
pub disputes: Vec<storage::Dispute>,
pub attempts: Option<Vec<storage::PaymentAttempt>>,
@@ -2652,7 +2657,10 @@ where
.as_ref()
.zip(payment_data.payment_attempt.payment_method_type.as_ref())
{
- if let Some(choice) = pre_routing_results.get(storage_pm_type) {
+ if let (Some(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(),
@@ -2687,6 +2695,12 @@ where
.attach_printable("Failed execution of straight through routing")?;
if check_eligibility {
+ #[cfg(feature = "business_profile_routing")]
+ let profile_id = payment_data.payment_intent.profile_id.clone();
+
+ #[cfg(not(feature = "business_profile_routing"))]
+ let _profile_id: Option<String> = None;
+
connectors = routing::perform_eligibility_analysis_with_fallback(
&state.clone(),
key_store,
@@ -2695,20 +2709,13 @@ where
&TransactionData::Payment(payment_data),
eligible_connectors,
#[cfg(feature = "business_profile_routing")]
- payment_data.payment_intent.profile_id.clone(),
+ profile_id,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed eligibility analysis and fallback")?;
}
- let first_connector_choice = connectors
- .first()
- .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)
- .into_report()
- .attach_printable("Empty connector list returned")?
- .clone();
-
let connector_data = connectors
.into_iter()
.map(|conn| {
@@ -2726,17 +2733,11 @@ where
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Invalid connector name received")?;
- routing_data.routed_through = Some(first_connector_choice.connector.to_string());
- #[cfg(feature = "connector_choice_mca_id")]
- {
- routing_data.merchant_connector_id = first_connector_choice.merchant_connector_id;
- }
- #[cfg(not(feature = "connector_choice_mca_id"))]
- {
- routing_data.business_sub_label = first_connector_choice.sub_label.clone();
- }
- routing_data.routing_info.algorithm = Some(routing_algorithm);
- return Ok(api::ConnectorCallType::Retryable(connector_data));
+ return decide_connector_for_token_based_mit_flow(
+ payment_data,
+ routing_data,
+ connector_data,
+ );
}
if let Some(ref routing_algorithm) = routing_data.routing_info.algorithm {
@@ -2748,6 +2749,12 @@ where
.attach_printable("Failed execution of straight through routing")?;
if check_eligibility {
+ #[cfg(feature = "business_profile_routing")]
+ let profile_id = payment_data.payment_intent.profile_id.clone();
+
+ #[cfg(not(feature = "business_profile_routing"))]
+ let _profile_id: Option<String> = None;
+
connectors = routing::perform_eligibility_analysis_with_fallback(
&state,
key_store,
@@ -2756,20 +2763,13 @@ where
&TransactionData::Payment(payment_data),
eligible_connectors,
#[cfg(feature = "business_profile_routing")]
- payment_data.payment_intent.profile_id.clone(),
+ profile_id,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed eligibility analysis and fallback")?;
}
- let first_connector_choice = connectors
- .first()
- .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)
- .into_report()
- .attach_printable("Empty connector list returned")?
- .clone();
-
let connector_data = connectors
.into_iter()
.map(|conn| {
@@ -2787,16 +2787,11 @@ where
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Invalid connector name received")?;
- routing_data.routed_through = Some(first_connector_choice.connector.to_string());
- #[cfg(feature = "connector_choice_mca_id")]
- {
- routing_data.merchant_connector_id = first_connector_choice.merchant_connector_id;
- }
- #[cfg(not(feature = "connector_choice_mca_id"))]
- {
- routing_data.business_sub_label = first_connector_choice.sub_label;
- }
- return Ok(api::ConnectorCallType::Retryable(connector_data));
+ return decide_connector_for_token_based_mit_flow(
+ payment_data,
+ routing_data,
+ connector_data,
+ );
}
route_connector_v1(
@@ -2804,13 +2799,107 @@ where
merchant_account,
business_profile,
key_store,
- &TransactionData::Payment(payment_data),
+ TransactionData::Payment(payment_data),
routing_data,
eligible_connectors,
)
.await
}
+pub fn decide_connector_for_token_based_mit_flow<F: Clone>(
+ payment_data: &mut PaymentData<F>,
+ routing_data: &mut storage::RoutingData,
+ connectors: Vec<api::ConnectorData>,
+) -> RouterResult<ConnectorCallType> {
+ if let Some((storage_enums::FutureUsage::OffSession, _)) = payment_data
+ .payment_intent
+ .setup_future_usage
+ .zip(payment_data.token_data.as_ref())
+ {
+ logger::debug!("performing routing for token-based MIT flow");
+
+ let payment_method_info = payment_data
+ .payment_method_info
+ .as_ref()
+ .get_required_value("payment_method_info")?;
+
+ let connector_mandate_details = payment_method_info
+ .connector_mandate_details
+ .clone()
+ .map(|details| {
+ details.parse_value::<storage::PaymentsMandateReference>("connector_mandate_details")
+ })
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("unable to deserialize connector mandate details")?
+ .get_required_value("connector_mandate_details")
+ .change_context(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)
+ .attach_printable("no eligible connector found for token-based MIT flow since there were no connector mandate details")?;
+
+ let mut connector_choice = None;
+ for connector_data in connectors {
+ if let Some(merchant_connector_id) = connector_data.merchant_connector_id.as_ref() {
+ if let Some(mandate_reference_record) =
+ connector_mandate_details.get(merchant_connector_id)
+ {
+ connector_choice = Some((connector_data, mandate_reference_record.clone()));
+ break;
+ }
+ }
+ }
+
+ let (chosen_connector_data, mandate_reference_record) = connector_choice
+ .get_required_value("connector_choice")
+ .change_context(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)
+ .attach_printable("no eligible connector found for token-based MIT payment")?;
+
+ routing_data.routed_through = Some(chosen_connector_data.connector_name.to_string());
+ #[cfg(feature = "connector_choice_mca_id")]
+ {
+ routing_data.merchant_connector_id =
+ chosen_connector_data.merchant_connector_id.clone();
+ }
+
+ payment_data.mandate_id = Some(payments_api::MandateIds {
+ mandate_id: None,
+ mandate_reference_id: Some(payments_api::MandateReferenceId::ConnectorMandateId(
+ payments_api::ConnectorMandateReferenceId {
+ connector_mandate_id: Some(
+ mandate_reference_record.connector_mandate_id.clone(),
+ ),
+ payment_method_id: Some(payment_method_info.payment_method_id.clone()),
+ update_history: None,
+ },
+ )),
+ });
+
+ payment_data.recurring_mandate_payment_data = Some(RecurringMandatePaymentData {
+ payment_method_type: mandate_reference_record.payment_method_type,
+ original_payment_authorized_amount: mandate_reference_record
+ .original_payment_authorized_amount,
+ original_payment_authorized_currency: mandate_reference_record
+ .original_payment_authorized_currency,
+ });
+
+ Ok(api::ConnectorCallType::PreDetermined(chosen_connector_data))
+ } else {
+ let first_choice = connectors
+ .first()
+ .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)
+ .into_report()
+ .attach_printable("no eligible connector found for payment")?
+ .clone();
+
+ routing_data.routed_through = Some(first_choice.connector_name.to_string());
+ #[cfg(feature = "connector_choice_mca_id")]
+ {
+ routing_data.merchant_connector_id = first_choice.merchant_connector_id;
+ }
+
+ Ok(api::ConnectorCallType::Retryable(connectors))
+ }
+}
+
pub fn should_add_task_to_process_tracker<F: Clone>(payment_data: &PaymentData<F>) -> bool {
let connector = payment_data.payment_attempt.connector.as_deref();
@@ -2940,7 +3029,7 @@ pub async fn route_connector_v1<F>(
merchant_account: &domain::MerchantAccount,
business_profile: &storage::business_profile::BusinessProfile,
key_store: &domain::MerchantKeyStore,
- transaction_data: &TransactionData<'_, F>,
+ transaction_data: TransactionData<'_, F>,
routing_data: &mut storage::RoutingData,
eligible_connectors: Option<Vec<api_models::enums::RoutableConnectors>>,
) -> RouterResult<ConnectorCallType>
@@ -2948,7 +3037,7 @@ where
F: Send + Clone,
{
#[allow(unused_variables)]
- let (profile_id, routing_algorithm) = match transaction_data {
+ let (profile_id, routing_algorithm) = match &transaction_data {
TransactionData::Payment(payment_data) => {
if cfg!(feature = "business_profile_routing") {
(
@@ -2983,7 +3072,7 @@ where
state,
&merchant_account.merchant_id,
algorithm_ref,
- transaction_data,
+ &transaction_data,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
@@ -2993,7 +3082,7 @@ where
key_store,
merchant_account.modified_at.assume_utc().unix_timestamp(),
connectors,
- transaction_data,
+ &transaction_data,
eligible_connectors,
#[cfg(feature = "business_profile_routing")]
profile_id,
@@ -3002,6 +3091,7 @@ where
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed eligibility analysis and fallback")?;
+ #[cfg(feature = "payouts")]
let first_connector_choice = connectors
.first()
.ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)
@@ -3009,17 +3099,6 @@ where
.attach_printable("Empty connector list returned")?
.clone();
- routing_data.routed_through = Some(first_connector_choice.connector.to_string());
-
- #[cfg(feature = "connector_choice_mca_id")]
- {
- routing_data.merchant_connector_id = first_connector_choice.merchant_connector_id;
- }
- #[cfg(not(feature = "connector_choice_mca_id"))]
- {
- routing_data.business_sub_label = first_connector_choice.sub_label;
- }
-
let connector_data = connectors
.into_iter()
.map(|conn| {
@@ -3037,7 +3116,27 @@ where
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Invalid connector name received")?;
- Ok(ConnectorCallType::Retryable(connector_data))
+ match transaction_data {
+ TransactionData::Payment(payment_data) => {
+ decide_connector_for_token_based_mit_flow(payment_data, routing_data, connector_data)
+ }
+
+ #[cfg(feature = "payouts")]
+ TransactionData::Payout(_) => {
+ routing_data.routed_through = Some(first_connector_choice.connector.to_string());
+
+ #[cfg(feature = "connector_choice_mca_id")]
+ {
+ routing_data.merchant_connector_id = first_connector_choice.merchant_connector_id;
+ }
+ #[cfg(not(feature = "connector_choice_mca_id"))]
+ {
+ routing_data.business_sub_label = first_connector_choice.sub_label;
+ }
+
+ Ok(ConnectorCallType::Retryable(connector_data))
+ }
+ }
}
#[instrument(skip_all)]
diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs
index 212e694ac92..efc0e8852da 100644
--- a/crates/router/src/core/payments/flows/authorize_flow.rs
+++ b/crates/router/src/core/payments/flows/authorize_flow.rs
@@ -100,6 +100,8 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu
merchant_account,
self.request.payment_method_type,
key_store,
+ Some(resp.request.amount),
+ Some(resp.request.currency),
))
.await?;
@@ -134,6 +136,8 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu
&merchant_account,
self.request.payment_method_type,
&key_store,
+ Some(resp.request.amount),
+ Some(resp.request.currency),
))
.await;
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 65342a1f06b..189a8a0a3ed 100644
--- a/crates/router/src/core/payments/flows/setup_mandate_flow.rs
+++ b/crates/router/src/core/payments/flows/setup_mandate_flow.rs
@@ -107,6 +107,8 @@ impl Feature<api::SetupMandate, types::SetupMandateRequestData> for types::Setup
merchant_account,
self.request.payment_method_type,
key_store,
+ resp.request.amount,
+ Some(resp.request.currency),
))
.await?;
@@ -244,6 +246,8 @@ impl types::SetupMandateRouterData {
merchant_account,
payment_method_type,
key_store,
+ resp.request.amount,
+ Some(resp.request.currency),
))
.await?;
@@ -330,6 +334,8 @@ impl types::SetupMandateRouterData {
merchant_account,
self.request.payment_method_type,
key_store,
+ resp.request.amount,
+ Some(resp.request.currency),
))
.await?
.0;
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 76ffed499d1..68821ee5032 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -1602,6 +1602,90 @@ pub async fn retrieve_card_with_permanent_token(
Ok(api::PaymentMethodData::Card(api_card))
}
+pub async fn retrieve_payment_method_from_db_with_token_data(
+ state: &AppState,
+ token_data: &storage::PaymentTokenData,
+) -> RouterResult<Option<storage::PaymentMethod>> {
+ match token_data {
+ storage::PaymentTokenData::PermanentCard(data) => {
+ if let Some(ref payment_method_id) = data.payment_method_id {
+ state
+ .store
+ .find_payment_method(payment_method_id)
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)
+ .attach_printable("error retrieving payment method from DB")
+ .map(Some)
+ } else {
+ Ok(None)
+ }
+ }
+
+ storage::PaymentTokenData::WalletToken(data) => state
+ .store
+ .find_payment_method(&data.payment_method_id)
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)
+ .attach_printable("error retrieveing payment method from DB")
+ .map(Some),
+
+ storage::PaymentTokenData::Temporary(_)
+ | storage::PaymentTokenData::TemporaryGeneric(_)
+ | storage::PaymentTokenData::Permanent(_)
+ | storage::PaymentTokenData::AuthBankDebit(_) => Ok(None),
+ }
+}
+
+pub async fn retrieve_payment_token_data(
+ state: &AppState,
+ token: String,
+ payment_method: Option<storage_enums::PaymentMethod>,
+) -> RouterResult<storage::PaymentTokenData> {
+ let redis_conn = state
+ .store
+ .get_redis_conn()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to get redis connection")?;
+
+ let key = format!(
+ "pm_token_{}_{}_hyperswitch",
+ token,
+ payment_method.get_required_value("payment_method")?
+ );
+
+ let token_data_string = redis_conn
+ .get_key::<Option<String>>(&key)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to fetch the token from redis")?
+ .ok_or(error_stack::Report::new(
+ errors::ApiErrorResponse::UnprocessableEntity {
+ message: "Token is invalid or expired".to_owned(),
+ },
+ ))?;
+
+ let token_data_result = token_data_string
+ .clone()
+ .parse_struct("PaymentTokenData")
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("failed to deserialize hyperswitch token data");
+
+ let token_data = match token_data_result {
+ Ok(data) => data,
+ Err(e) => {
+ // The purpose of this logic is backwards compatibility to support tokens
+ // in redis that might be following the old format.
+ if token_data_string.starts_with('{') {
+ return Err(e);
+ } else {
+ storage::PaymentTokenData::temporary_generic(token_data_string)
+ }
+ }
+ };
+
+ Ok(token_data)
+}
+
pub async fn make_pm_data<'a, F: Clone, R, Ctx: PaymentMethodRetrieve>(
operation: BoxedOperation<'a, F, R, Ctx>,
state: &'a AppState,
@@ -1630,72 +1714,13 @@ pub async fn make_pm_data<'a, F: Clone, R, Ctx: PaymentMethodRetrieve>(
}
}
- let token = payment_data.token.clone();
-
- let hyperswitch_token = match payment_data.mandate_id {
- Some(_) => token.map(storage::PaymentTokenData::temporary_generic),
- None => {
- if let Some(token) = token {
- let redis_conn = state
- .store
- .get_redis_conn()
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to get redis connection")?;
-
- let key = format!(
- "pm_token_{}_{}_hyperswitch",
- token,
- payment_data
- .payment_attempt
- .payment_method
- .to_owned()
- .get_required_value("payment_method")?,
- );
-
- let token_data_string = redis_conn
- .get_key::<Option<String>>(&key)
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to fetch the token from redis")?
- .ok_or(error_stack::Report::new(
- errors::ApiErrorResponse::UnprocessableEntity {
- message: "Token is invalid or expired".to_owned(),
- },
- ))?;
-
- let token_data_result = token_data_string
- .clone()
- .parse_struct("PaymentTokenData")
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("failed to deserialize hyperswitch token data");
-
- let token_data = match token_data_result {
- Ok(data) => data,
- Err(e) => {
- // The purpose of this logic is backwards compatibility to support tokens
- // in redis that might be following the old format.
- if token_data_string.starts_with('{') {
- return Err(e);
- } else {
- storage::PaymentTokenData::temporary_generic(token_data_string)
- }
- }
- };
-
- Some(token_data)
- } else {
- None
- }
- }
- };
-
// TODO: Handle case where payment method and token both are present in request properly.
- let (payment_method, pm_id) = match (request, hyperswitch_token) {
+ let (payment_method, pm_id) = match (request, payment_data.token_data.as_ref()) {
(_, Some(hyperswitch_token)) => {
let pm_data = Ctx::retrieve_payment_method_with_token(
state,
merchant_key_store,
- &hyperswitch_token,
+ hyperswitch_token,
&payment_data.payment_intent,
card_token_data.as_ref(),
customer,
diff --git a/crates/router/src/core/payments/operations/payment_approve.rs b/crates/router/src/core/payments/operations/payment_approve.rs
index ca6ed3e4ebd..6ad14d8fc4e 100644
--- a/crates/router/src/core/payments/operations/payment_approve.rs
+++ b/crates/router/src/core/payments/operations/payment_approve.rs
@@ -149,6 +149,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
setup_mandate: None,
customer_acceptance: None,
token: None,
+ token_data: None,
address: PaymentAddress {
shipping: shipping_address.as_ref().map(|a| a.into()),
billing: billing_address.as_ref().map(|a| a.into()),
@@ -158,6 +159,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
},
confirm: None,
payment_method_data: None,
+ payment_method_info: None,
force_sync: None,
refunds: vec![],
disputes: vec![],
diff --git a/crates/router/src/core/payments/operations/payment_cancel.rs b/crates/router/src/core/payments/operations/payment_cancel.rs
index 7d5bf73fc1f..2439646b3da 100644
--- a/crates/router/src/core/payments/operations/payment_cancel.rs
+++ b/crates/router/src/core/payments/operations/payment_cancel.rs
@@ -157,6 +157,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
setup_mandate: None,
customer_acceptance: None,
token: None,
+ token_data: None,
address: PaymentAddress {
shipping: shipping_address.as_ref().map(|a| a.into()),
billing: billing_address.as_ref().map(|a| a.into()),
@@ -166,6 +167,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
},
confirm: None,
payment_method_data: None,
+ payment_method_info: None,
force_sync: None,
refunds: vec![],
disputes: vec![],
diff --git a/crates/router/src/core/payments/operations/payment_capture.rs b/crates/router/src/core/payments/operations/payment_capture.rs
index d67151897aa..d643c86698d 100644
--- a/crates/router/src/core/payments/operations/payment_capture.rs
+++ b/crates/router/src/core/payments/operations/payment_capture.rs
@@ -202,6 +202,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
setup_mandate: None,
customer_acceptance: None,
token: None,
+ token_data: None,
address: payments::PaymentAddress {
shipping: shipping_address.as_ref().map(|a| a.into()),
billing: billing_address.as_ref().map(|a| a.into()),
@@ -211,6 +212,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
},
confirm: None,
payment_method_data: None,
+ payment_method_info: None,
refunds: vec![],
disputes: vec![],
attempts: None,
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 22ba50c07b9..79701db575b 100644
--- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs
+++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs
@@ -131,6 +131,12 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
}
}
+ let token_data = if let Some(token) = token.clone() {
+ Some(helpers::retrieve_payment_token_data(state, token, payment_method).await?)
+ } else {
+ None
+ };
+
payment_attempt.payment_method = payment_method.or(payment_attempt.payment_method);
payment_attempt.browser_info = browser_info;
payment_attempt.payment_method_type =
@@ -247,6 +253,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
setup_mandate,
customer_acceptance: None,
token,
+ token_data,
address: PaymentAddress {
shipping: shipping_address.as_ref().map(|a| a.into()),
billing: billing_address.as_ref().map(|a| a.into()),
@@ -259,6 +266,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
.payment_method_data
.as_ref()
.map(|pmd| pmd.payment_method_data.clone()),
+ payment_method_info: None,
force_sync: None,
refunds: vec![],
disputes: vec![],
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index 2f548129a65..96de0cc924b 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -383,6 +383,23 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
&token,
)?;
+ let (token_data, payment_method_info) = if let Some(token) = token.clone() {
+ let token_data = helpers::retrieve_payment_token_data(
+ state,
+ token,
+ payment_method.or(payment_attempt.payment_method),
+ )
+ .await?;
+
+ let payment_method_info =
+ helpers::retrieve_payment_method_from_db_with_token_data(state, &token_data)
+ .await?;
+
+ (Some(token_data), payment_method_info)
+ } else {
+ (None, None)
+ };
+
payment_attempt.payment_method = payment_method.or(payment_attempt.payment_method);
payment_attempt.browser_info = browser_info;
payment_attempt.payment_method_type =
@@ -548,6 +565,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
setup_mandate,
customer_acceptance,
token,
+ token_data,
address: PaymentAddress {
shipping: shipping_address.as_ref().map(|a| a.into()),
billing: billing_address.as_ref().map(|a| a.into()),
@@ -557,6 +575,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
},
confirm: request.confirm,
payment_method_data: payment_method_data_after_card_bin_call,
+ payment_method_info,
force_sync: None,
refunds: vec![],
disputes: vec![],
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index b4ae0285dd1..bcc13ea1cef 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -302,7 +302,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
mandate_obj.connector_mandate_ids,
) {
(Some(network_tx_id), _) => Ok(api_models::payments::MandateIds {
- mandate_id: mandate_obj.mandate_id,
+ mandate_id: Some(mandate_obj.mandate_id),
mandate_reference_id: Some(
api_models::payments::MandateReferenceId::NetworkMandateId(
network_tx_id,
@@ -314,7 +314,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
.change_context(errors::ApiErrorResponse::MandateNotFound)
.map(|connector_id: api_models::payments::ConnectorMandateReferenceId| {
api_models::payments::MandateIds {
- mandate_id: mandate_obj.mandate_id,
+ mandate_id: Some(mandate_obj.mandate_id),
mandate_reference_id: Some(api_models::payments::MandateReferenceId::ConnectorMandateId(
api_models::payments::ConnectorMandateReferenceId{
connector_mandate_id: connector_id.connector_mandate_id,
@@ -325,7 +325,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
}
}),
(_, _) => Ok(api_models::payments::MandateIds {
- mandate_id: mandate_obj.mandate_id,
+ mandate_id: Some(mandate_obj.mandate_id),
mandate_reference_id: None,
}),
}
@@ -390,6 +390,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
setup_mandate,
customer_acceptance,
token,
+ token_data: None,
address: PaymentAddress {
shipping: shipping_address.as_ref().map(|a| a.into()),
billing: billing_address.as_ref().map(|a| a.into()),
@@ -399,6 +400,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
},
confirm: request.confirm,
payment_method_data: payment_method_data_after_card_bin_call,
+ payment_method_info: None,
refunds: vec![],
disputes: vec![],
attempts: None,
diff --git a/crates/router/src/core/payments/operations/payment_reject.rs b/crates/router/src/core/payments/operations/payment_reject.rs
index 66bab03d047..36197a9463b 100644
--- a/crates/router/src/core/payments/operations/payment_reject.rs
+++ b/crates/router/src/core/payments/operations/payment_reject.rs
@@ -145,6 +145,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
setup_mandate: None,
customer_acceptance: None,
token: None,
+ token_data: None,
address: PaymentAddress {
shipping: shipping_address.as_ref().map(|a| a.into()),
billing: billing_address.as_ref().map(|a| a.into()),
@@ -154,6 +155,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
},
confirm: None,
payment_method_data: None,
+ payment_method_info: None,
force_sync: None,
refunds: vec![],
disputes: vec![],
diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs
index 18e568eb9b8..eaded6b5e65 100644
--- a/crates/router/src/core/payments/operations/payment_response.rs
+++ b/crates/router/src/core/payments/operations/payment_response.rs
@@ -654,7 +654,7 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
mandate_id: payment_data
.mandate_id
.clone()
- .map(|mandate| mandate.mandate_id),
+ .and_then(|mandate| mandate.mandate_id),
connector_metadata,
payment_token: None,
error_code: error_status.clone(),
@@ -844,7 +844,7 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
.or(payment_data
.mandate_id
.clone()
- .map(|mandate_ids| mandate_ids.mandate_id));
+ .and_then(|mandate_ids| mandate_ids.mandate_id));
let m_router_data_response = router_data.response.clone();
let mandate_update_fut = tokio::spawn(
async move {
diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs
index e64b41ed383..d498e1baca4 100644
--- a/crates/router/src/core/payments/operations/payment_session.rs
+++ b/crates/router/src/core/payments/operations/payment_session.rs
@@ -169,6 +169,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
mandate_connector: None,
customer_acceptance: None,
token: None,
+ token_data: None,
setup_mandate: None,
address: payments::PaymentAddress {
shipping: shipping_address.as_ref().map(|a| a.into()),
@@ -179,6 +180,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
},
confirm: None,
payment_method_data: None,
+ payment_method_info: None,
force_sync: None,
refunds: vec![],
disputes: vec![],
diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rs
index 885d2593ba8..f1264868ff7 100644
--- a/crates/router/src/core/payments/operations/payment_start.rs
+++ b/crates/router/src/core/payments/operations/payment_start.rs
@@ -114,6 +114,15 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
)
.await?;
+ let token_data = if let Some(token) = payment_attempt.payment_token.clone() {
+ Some(
+ helpers::retrieve_payment_token_data(state, token, payment_attempt.payment_method)
+ .await?,
+ )
+ } else {
+ None
+ };
+
payment_intent.shipping_address_id = shipping_address.clone().map(|i| i.address_id);
payment_intent.billing_address_id = billing_address.clone().map(|i| i.address_id);
@@ -147,6 +156,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
setup_mandate: None,
customer_acceptance: None,
token: payment_attempt.payment_token.clone(),
+ token_data,
address: PaymentAddress {
shipping: shipping_address.as_ref().map(|a| a.into()),
billing: billing_address.as_ref().map(|a| a.into()),
@@ -157,6 +167,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
confirm: Some(payment_attempt.confirm),
payment_attempt,
payment_method_data: None,
+ payment_method_info: None,
force_sync: None,
refunds: vec![],
disputes: vec![],
diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs
index f36a2eea81d..66f0527c35d 100644
--- a/crates/router/src/core/payments/operations/payment_status.rs
+++ b/crates/router/src/core/payments/operations/payment_status.rs
@@ -410,13 +410,14 @@ async fn get_tracker_for_sync<
.mandate_id
.clone()
.map(|id| api_models::payments::MandateIds {
- mandate_id: id,
+ mandate_id: Some(id),
mandate_reference_id: None,
}),
mandate_connector: None,
setup_mandate: None,
customer_acceptance: None,
token: None,
+ token_data: None,
address: PaymentAddress {
shipping: shipping_address.as_ref().map(|a| a.into()),
billing: billing_address.as_ref().map(|a| a.into()),
@@ -426,6 +427,7 @@ async fn get_tracker_for_sync<
},
confirm: Some(request.force_sync),
payment_method_data: None,
+ payment_method_info: None,
force_sync: Some(
request.force_sync
&& (helpers::check_force_psync_precondition(&payment_attempt.status)
diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs
index c5fda22ed87..0ce77dfcd13 100644
--- a/crates/router/src/core/payments/operations/payment_update.rs
+++ b/crates/router/src/core/payments/operations/payment_update.rs
@@ -254,6 +254,12 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
)?;
}
+ let token_data = if let Some(token) = token.clone() {
+ Some(helpers::retrieve_payment_token_data(state, token, payment_method).await?)
+ } else {
+ None
+ };
+
let mandate_id = request
.mandate_id
.as_ref()
@@ -268,7 +274,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
mandate_obj.connector_mandate_ids,
) {
(Some(network_tx_id), _) => Ok(api_models::payments::MandateIds {
- mandate_id: mandate_obj.mandate_id,
+ mandate_id: Some(mandate_obj.mandate_id),
mandate_reference_id: Some(
api_models::payments::MandateReferenceId::NetworkMandateId(
network_tx_id,
@@ -280,14 +286,14 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
.change_context(errors::ApiErrorResponse::MandateNotFound)
.map(|connector_id: api_models::payments::ConnectorMandateReferenceId| {
api_models::payments::MandateIds {
- mandate_id: mandate_obj.mandate_id,
+ mandate_id: Some(mandate_obj.mandate_id),
mandate_reference_id: Some(api_models::payments::MandateReferenceId::ConnectorMandateId(
api_models::payments::ConnectorMandateReferenceId {connector_mandate_id:connector_id.connector_mandate_id,payment_method_id:connector_id.payment_method_id, update_history: None },
))
}
}),
(_, _) => Ok(api_models::payments::MandateIds {
- mandate_id: mandate_obj.mandate_id,
+ mandate_id: Some(mandate_obj.mandate_id),
mandate_reference_id: None,
}),
}
@@ -383,6 +389,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
mandate_id,
mandate_connector,
token,
+ token_data,
setup_mandate,
customer_acceptance,
address: PaymentAddress {
@@ -395,6 +402,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
.payment_method_data
.as_ref()
.map(|pmd| pmd.payment_method_data.clone()),
+ payment_method_info: None,
force_sync: None,
refunds: vec![],
disputes: vec![],
diff --git a/crates/router/src/core/payments/operations/payments_incremental_authorization.rs b/crates/router/src/core/payments/operations/payments_incremental_authorization.rs
index dbdf1c062ac..0157822cdf8 100644
--- a/crates/router/src/core/payments/operations/payments_incremental_authorization.rs
+++ b/crates/router/src/core/payments/operations/payments_incremental_authorization.rs
@@ -122,6 +122,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
setup_mandate: None,
customer_acceptance: None,
token: None,
+ token_data: None,
address: PaymentAddress {
billing: None,
shipping: None,
@@ -129,6 +130,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
},
confirm: None,
payment_method_data: None,
+ payment_method_info: None,
force_sync: None,
refunds: vec![],
disputes: vec![],
diff --git a/crates/router/src/core/payments/retry.rs b/crates/router/src/core/payments/retry.rs
index 91b6061c111..2af73f29909 100644
--- a/crates/router/src/core/payments/retry.rs
+++ b/crates/router/src/core/payments/retry.rs
@@ -377,7 +377,7 @@ where
mandate_id: payment_data
.mandate_id
.clone()
- .map(|mandate| mandate.mandate_id),
+ .and_then(|mandate| mandate.mandate_id),
connector_metadata,
payment_token: None,
error_code: None,
diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs
index 7aaaaed92aa..4628f027a05 100644
--- a/crates/router/src/core/payments/tokenization.rs
+++ b/crates/router/src/core/payments/tokenization.rs
@@ -39,6 +39,8 @@ pub async fn save_payment_method<F: Clone, FData>(
merchant_account: &domain::MerchantAccount,
payment_method_type: Option<storage_enums::PaymentMethodType>,
key_store: &domain::MerchantKeyStore,
+ amount: Option<i64>,
+ currency: Option<storage_enums::Currency>,
) -> RouterResult<(Option<String>, Option<common_enums::PaymentMethodStatus>)>
where
FData: mandate::MandateBehaviour,
@@ -94,7 +96,13 @@ where
.map(|future_usage| future_usage == storage_enums::FutureUsage::OffSession)
.unwrap_or(false)
{
- add_connector_mandate_details_in_payment_method(responses, connector)
+ add_connector_mandate_details_in_payment_method(
+ responses,
+ payment_method_type,
+ amount,
+ currency,
+ connector,
+ )
} else {
None
}
@@ -648,6 +656,9 @@ pub async fn add_payment_method_token<F: Clone, T: types::Tokenizable + Clone>(
fn add_connector_mandate_details_in_payment_method(
resp: types::PaymentsResponseData,
+ payment_method_type: Option<storage_enums::PaymentMethodType>,
+ authorized_amount: Option<i64>,
+ authorized_currency: Option<storage_enums::Currency>,
connector: &api::ConnectorData,
) -> Option<storage::PaymentsMandateReference> {
let mut mandate_details = HashMap::new();
@@ -665,8 +676,20 @@ fn add_connector_mandate_details_in_payment_method(
_ => None,
};
- if let Some(mca_id) = connector.merchant_connector_id.clone() {
- mandate_details.insert(mca_id, connector_mandate_id);
+ if let Some((mca_id, connector_mandate_id)) = connector
+ .merchant_connector_id
+ .clone()
+ .zip(connector_mandate_id)
+ {
+ mandate_details.insert(
+ mca_id,
+ storage::PaymentsMandateReferenceRecord {
+ connector_mandate_id,
+ payment_method_type,
+ original_payment_authorized_amount: authorized_amount,
+ original_payment_authorized_currency: authorized_currency,
+ },
+ );
Some(storage::PaymentsMandateReference(mandate_details))
} else {
None
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index 8e5b2c9199e..0ae04aaddce 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -327,7 +327,9 @@ where
phone: customer
.as_ref()
.and_then(|cus| cus.phone.as_ref().map(|s| s.to_owned())),
- mandate_id: data.mandate_id.map(|mandate_ids| mandate_ids.mandate_id),
+ mandate_id: data
+ .mandate_id
+ .and_then(|mandate_ids| mandate_ids.mandate_id),
payment_method: data.payment_attempt.payment_method,
payment_method_data: payment_method_data_response,
payment_token: data.token,
diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs
index 9fd7458155a..847c555a86d 100644
--- a/crates/router/src/core/payouts/helpers.rs
+++ b/crates/router/src/core/payouts/helpers.rs
@@ -600,7 +600,7 @@ pub async fn decide_payout_connector(
merchant_account,
&payout_data.business_profile,
key_store,
- &TransactionData::<()>::Payout(payout_data),
+ TransactionData::<()>::Payout(payout_data),
routing_data,
eligible_connectors,
)
diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rs
index 31a2e05dd79..0d9c7f4f62c 100644
--- a/crates/router/src/core/routing.rs
+++ b/crates/router/src/core/routing.rs
@@ -36,12 +36,11 @@ use crate::{core::errors, services::api as service_api, types::storage};
#[cfg(feature = "business_profile_routing")]
use crate::{errors, services::api as service_api};
-#[derive(Clone)]
pub enum TransactionData<'a, F>
where
F: Clone,
{
- Payment(&'a payments::PaymentData<F>),
+ Payment(&'a mut payments::PaymentData<F>),
#[cfg(feature = "payouts")]
Payout(&'a payouts::PayoutData),
}
diff --git a/crates/router/src/types/storage/payment_method.rs b/crates/router/src/types/storage/payment_method.rs
index 8edfb8b36d8..d3339b7c4be 100644
--- a/crates/router/src/types/storage/payment_method.rs
+++ b/crates/router/src/types/storage/payment_method.rs
@@ -1,4 +1,7 @@
-use std::collections::HashMap;
+use std::{
+ collections::HashMap,
+ ops::{Deref, DerefMut},
+};
use api_models::payment_methods;
use diesel_models::enums;
@@ -40,7 +43,7 @@ pub struct WalletTokenData {
pub payment_method_id: String,
}
-#[derive(Debug, serde::Serialize, serde::Deserialize)]
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum PaymentTokenData {
// The variants 'Temporary' and 'Permanent' are added for backwards compatibility
@@ -76,4 +79,26 @@ impl PaymentTokenData {
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
-pub struct PaymentsMandateReference(pub HashMap<String, Option<String>>);
+pub struct PaymentsMandateReferenceRecord {
+ pub connector_mandate_id: String,
+ pub payment_method_type: Option<common_enums::PaymentMethodType>,
+ pub original_payment_authorized_amount: Option<i64>,
+ pub original_payment_authorized_currency: Option<common_enums::Currency>,
+}
+
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+pub struct PaymentsMandateReference(pub HashMap<String, PaymentsMandateReferenceRecord>);
+
+impl Deref for PaymentsMandateReference {
+ type Target = HashMap<String, PaymentsMandateReferenceRecord>;
+
+ fn deref(&self) -> &Self::Target {
+ &self.0
+ }
+}
+
+impl DerefMut for PaymentsMandateReference {
+ fn deref_mut(&mut self) -> &mut Self::Target {
+ &mut self.0
+ }
+}
|
2024-03-07T12:39:39Z
|
## 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 routing support for token-based MIT payments. Basically, the merchant can have their customers set up their payment method for off session payments with Hyperswitch. Behind the scenes, Hyperswitch sets up an MIT/Mandate with the connector.
Now, when the merchant wants to do off-session payments using the customer's saved payment method by using a token to select the payment method, the backend needs to ensure that the payment goes through only those connectors for which that payment method is set up for MITs. This PR adds this 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).
-->
The merchant may want to do off-session payments by passing a payment method token on behalf of their customers. This would require the smart router to choose an appropriate connector for the payment on the basis of whether the selected payment method is set up with the connector for off-session MIT payments.
## 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 Merchant Account, and a Merchant Connector Account (preferably Cybersource)
2. Create and Confirm a `Setup Mandate` request
```bash
curl --location 'http://127.0.0.1:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_OnB9g3l1v3cqPalObMlJ874jZerIsl9hlNCoTdXzNyiB2K7Edrp3wEQYmdmnXFJM' \
--data-raw '{
"amount": 0,
"currency": "USD",
"confirm": true,
"profile_id": "pro_9ci3SqA4bSAe7g3C7jCp",
"capture_method": "automatic",
"customer_id": "MyCustomer123456",
"email": "guest@example.com",
"setup_future_usage": "off_session",
"customer_acceptance": {
"acceptance_type": "online"
},
"payment_method": "card",
"payment_method_type": "debit",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": "Test Holder",
"card_cvc": "737"
}
},
"payment_type": "setup_mandate",
"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"
}'
```
this will set the given card up for token-based MIT payments, and associate the connector MIT/Mandate details with the saved payment method in DB as shown below in the `connector_mandate_details` column
<img width="1727" alt="image" src="https://github.com/juspay/hyperswitch/assets/47862918/4c8aefe5-3079-43df-ac13-3226a291f006">
3. Next, to make a token-based MIT payment, Create a payment with `setup_future_usage = off_session`
```bash
curl --location 'http://127.0.0.1:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_hOic0bCxCZdrp9ShPzyl9b80NQgr2m4vy4gBVyKbKbWNNRCiNBm9yCA5D7McybRs' \
--data-raw '{
"amount": 499,
"currency": "USD",
"confirm": false,
"profile_id": "pro_tsOrBWXnZfzYRJ9Jm7Dk",
"capture_method": "automatic",
"customer_id": "MyCustomer123456",
"email": "guest@example.com",
"setup_future_usage": "off_session",
"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"
}'
```
4. Do a list customer payment methods call and confirm the payment with the token (no need to pass `card_cvc`)
```bash
curl --location 'http://127.0.0.1:8080/payments/pay_5C8NWON1GUFGbMLR3tXx/confirm' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_hOic0bCxCZdrp9ShPzyl9b80NQgr2m4vy4gBVyKbKbWNNRCiNBm9yCA5D7McybRs' \
--data '{
"payment_token": "token_ZTiG3Qz4ajaZB1MnBcmQ",
"payment_method": "card"
}'
```
This is treated as a token-based MIT payment since we passed `setup_future_usage = off_session` in create, and are confirming the payment with the token. Routing will detect this, get the `connector_mandate_details` from the payment method object associated with the token, and do a recurring mandate payment using the connector mandate details. Additionally, routing will ensure that the connector will be picked for a token-based MIT payment if and only if it has some connector mandate details saved in the payment method object. Following is the connector request sent by the backend to cybersource.
```json
{"processingInformation":{"actionList":null,"actionTokenTypes":null,"authorizationOptions":{"initiator":null,"merchantIntitiatedTransaction":{"reason":null,"originalAuthorizedAmount":"0.00"}},"commerceIndicator":"internet","capture":true,"captureOptions":null,"paymentSolution":null},"paymentInformation":{"paymentInstrument":{"id":"1323EB5C00917EC2E063A2598D0A69D7"}},"orderInformation":{"amountDetails":{"totalAmount":"2.00","currency":"USD"},"billTo":{"firstName":"One","lastName":"Two","address1":"here","locality":"bengaluru","administrativeArea":"Karnataka","postalCode":"560095","country":"IN","email":"guest@example.com"}},"clientReferenceInformation":{"code":"pay_iCiIdD8UqO3SdfAxGRrI_1"}}
```
We can see that `paymentInstrument` was set to the connector mandate ID by Routing, thus turning it into a recurring MIT payment.
5. To test and ensure that Routing picks a connector for token-based MIT payments if and only if it has connector_mandate_details for that connector, create another merchant connector account with a different connector `Y`.
6. Repeat steps 3 and 4 but in the confirm call, pass a `"routing"` value to force straight through routing to pick `Y`.
```bash
curl --location 'http://127.0.0.1:8080/payments/pay_5C8NWON1GUFGbMLR3tXx/confirm' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_hOic0bCxCZdrp9ShPzyl9b80NQgr2m4vy4gBVyKbKbWNNRCiNBm9yCA5D7McybRs' \
--data '{
"payment_token": "token_ZTiG3Qz4ajaZB1MnBcmQ",
"routing": {
"type": "single",
"data": {
"connector": "stripe",
"merchant_connector_id": "mca_hji9rSpSJPUOYn2A9yL9"
}
},
"payment_method": "card"
}'
```
Even tho we are forcing connector `Y` for the token-based MIT payment, Routing will detect that the chosen payment method does not have any MIT/Mandate set up with `Y` by checking the `connector_mandate_details` field in the payment method record, and automatically fall back to the first connector.
<img width="552" alt="image" src="https://github.com/juspay/hyperswitch/assets/47862918/5eb49d36-0c6b-43d6-8bae-9f9bf45bcd31">
## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
7391416e2473eab0474bd01bb155a9ecc96da263
|
|
juspay/hyperswitch
|
juspay__hyperswitch-3868
|
Bug: [FEATURE] : [Multisafepay] mask pii information in connector request and response
### Feature Description
Mask pii information passed and received in the connector request and response
### Possible Implementation
Refactor all sensitive response and request fields secret
### 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/masking/src/serde.rs b/crates/masking/src/serde.rs
index bb81717fd67..a96a87f05c8 100644
--- a/crates/masking/src/serde.rs
+++ b/crates/masking/src/serde.rs
@@ -27,6 +27,7 @@ pub trait SerializableSecret: Serialize {}
impl SerializableSecret for Value {}
impl SerializableSecret for u8 {}
impl SerializableSecret for u16 {}
+impl SerializableSecret for i32 {}
impl<'de, T, I> Deserialize<'de> for Secret<T, I>
where
diff --git a/crates/router/src/connector/multisafepay/transformers.rs b/crates/router/src/connector/multisafepay/transformers.rs
index 86096ed508b..f6051ea05de 100644
--- a/crates/router/src/connector/multisafepay/transformers.rs
+++ b/crates/router/src/connector/multisafepay/transformers.rs
@@ -1,4 +1,4 @@
-use common_utils::pii::Email;
+use common_utils::pii::{Email, IpAddress};
use masking::ExposeInterface;
use serde::{Deserialize, Serialize};
use url::Url;
@@ -68,7 +68,7 @@ pub enum Gateway {
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct Coupons {
- pub allow: Option<Vec<String>>,
+ pub allow: Option<Vec<Secret<String>>>,
}
#[serde_with::skip_serializing_none]
@@ -126,20 +126,20 @@ pub struct Browser {
pub struct Customer {
pub browser: Option<Browser>,
pub locale: Option<String>,
- pub ip_address: Option<String>,
- pub forward_ip: Option<String>,
- pub first_name: Option<String>,
- pub last_name: Option<String>,
- pub gender: Option<String>,
- pub birthday: Option<String>,
- pub address1: Option<String>,
- pub address2: Option<String>,
- pub house_number: Option<String>,
- pub zip_code: Option<String>,
+ pub ip_address: Option<Secret<String, IpAddress>>,
+ pub forward_ip: Option<Secret<String, IpAddress>>,
+ pub first_name: Option<Secret<String>>,
+ pub last_name: Option<Secret<String>>,
+ pub gender: Option<Secret<String>>,
+ pub birthday: Option<Secret<String>>,
+ pub address1: Option<Secret<String>>,
+ pub address2: Option<Secret<String>>,
+ pub house_number: Option<Secret<String>>,
+ pub zip_code: Option<Secret<String>>,
pub city: Option<String>,
pub state: Option<String>,
pub country: Option<String>,
- pub phone: Option<String>,
+ pub phone: Option<Secret<String>>,
pub email: Option<Email>,
pub user_agent: Option<String>,
pub referrer: Option<String>,
@@ -150,7 +150,7 @@ pub struct Customer {
pub struct CardInfo {
pub card_number: Option<cards::CardNumber>,
pub card_holder_name: Option<Secret<String>>,
- pub card_expiry_date: Option<i32>,
+ pub card_expiry_date: Option<Secret<i32>>,
pub card_cvc: Option<Secret<String>>,
pub flexible_3d: Option<bool>,
pub moto: Option<bool>,
@@ -159,7 +159,7 @@ pub struct CardInfo {
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct GpayInfo {
- pub payment_token: Option<String>,
+ pub payment_token: Option<Secret<String>>,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
@@ -242,7 +242,7 @@ pub struct MultisafepayPaymentsRequest {
pub shopping_cart: Option<ShoppingCart>,
pub items: Option<String>,
pub recurring_model: Option<MandateType>,
- pub recurring_id: Option<String>,
+ pub recurring_id: Option<Secret<String>>,
pub capture: Option<String>,
pub days_active: Option<i32>,
pub seconds_active: Option<i32>,
@@ -423,7 +423,7 @@ impl TryFrom<&MultisafepayRouterData<&types::PaymentsAuthorizeRouterData>>
let gateway_info = match item.router_data.request.payment_method_data {
api::PaymentMethodData::Card(ref ccard) => Some(GatewayInfo::Card(CardInfo {
card_number: Some(ccard.card_number.clone()),
- card_expiry_date: Some(
+ card_expiry_date: Some(Secret::new(
(format!(
"{}{}",
ccard.get_card_expiry_year_2_digit()?.expose(),
@@ -431,7 +431,7 @@ impl TryFrom<&MultisafepayRouterData<&types::PaymentsAuthorizeRouterData>>
))
.parse::<i32>()
.unwrap_or_default(),
- ),
+ )),
card_cvc: Some(ccard.card_cvc.clone()),
card_holder_name: None,
flexible_3d: None,
@@ -442,7 +442,9 @@ impl TryFrom<&MultisafepayRouterData<&types::PaymentsAuthorizeRouterData>>
api::WalletData::GooglePay(ref google_pay) => {
Some(GatewayInfo::Wallet(WalletInfo::GooglePay({
GpayInfo {
- payment_token: Some(google_pay.tokenization_data.token.clone()),
+ payment_token: Some(Secret::new(
+ google_pay.tokenization_data.token.clone(),
+ )),
}
})))
}
@@ -543,7 +545,7 @@ impl TryFrom<&MultisafepayRouterData<&types::PaymentsAuthorizeRouterData>>
.and_then(|mandate_ids| match mandate_ids.mandate_reference_id {
Some(api_models::payments::MandateReferenceId::ConnectorMandateId(
connector_mandate_ids,
- )) => connector_mandate_ids.connector_mandate_id,
+ )) => connector_mandate_ids.connector_mandate_id.map(Secret::new),
_ => None,
}),
days_active: Some(30),
@@ -619,13 +621,13 @@ pub struct Data {
#[derive(Default, Debug, Clone, Serialize, Deserialize, Eq, PartialEq)]
pub struct MultisafepayPaymentDetails {
- pub account_holder_name: Option<String>,
- pub account_id: Option<String>,
- pub card_expiry_date: Option<i32>,
+ pub account_holder_name: Option<Secret<String>>,
+ pub account_id: Option<Secret<String>>,
+ pub card_expiry_date: Option<Secret<String>>,
pub external_transaction_id: Option<serde_json::Value>,
- pub last4: Option<serde_json::Value>,
+ pub last4: Option<Secret<String>>,
pub recurring_flow: Option<String>,
- pub recurring_id: Option<String>,
+ pub recurring_id: Option<Secret<String>>,
pub recurring_model: Option<String>,
#[serde(rename = "type")]
pub payment_type: Option<String>,
@@ -685,7 +687,7 @@ impl<F, T>
.payment_details
.and_then(|payment_details| payment_details.recurring_id)
.map(|id| types::MandateReference {
- connector_mandate_id: Some(id),
+ connector_mandate_id: Some(id.expose()),
payment_method_id: None,
}),
connector_metadata: None,
|
2024-02-28T11:15:44Z
|
## 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 -->
Mask pii information passed and received in the connector request and response for Mulisafepay.
## Test Case
<!--
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 card payment
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key:{{api_key}}' \
--data-raw '{
"amount": 6540,
"currency": "USD",
"confirm": true,
"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": "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"
}
},
"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"
},
"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"
}
}
}'
```
2. Check if `apple_pay_payment_token` in the `masked_response` is masked
```
curl --location '{{base_url}}/analytics/v1/connector_event_logs?type=Payment&payment_id={{payment_id}}' \
--header 'sec-ch-ua: "Not A(Brand";v="99", "Google Chrome";v="121", "Chromium";v="121"' \
--header 'sec-ch-ua-mobile: ?0' \
--header 'authorization: Bearer JWT_token' \
--header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36' \
--header 'Content-Type: application/json' \
--header 'Referer: https://integ.hyperswitch.io/' \
--header 'api-key: {{api-key}}' \
--header 'sec-ch-ua-platform: "macOS"'
```
Response
```
request \":\"{\\\"type\\\":\\\"direct\\\",\\\"gateway\\\":\\\"VISA\\\",\\\"order_id\\\":\\\"pay_aqRMznVMpndvmmh3IweN_1\\\",\\\"currency\\\":\\\"USD\\\",\\\"amount\\\":6540,\\\"description\\\":\\\"Its my first payment request\\\",\\\"payment_options\\\":{\\\"redirect_url\\\":\\\"http://localhost:8080/payments/pay_aqRMznVMpndvmmh3IweN/merchant_1709116328/redirect/response/multisafepay\\\",\\\"cancel_url\\\":\\\"http://localhost:8080/payments/pay_aqRMznVMpndvmmh3IweN/merchant_1709116328/redirect/response/multisafepay\\\"},\\\"customer\\\":{\\\"email\\\":\\\"*********@gmail.com\\\",\\\"reference\\\":\\\"pay_aqRMznVMpndvmmh3IweN_1\\\"},\\\"gateway_info\\\":{\\\"card_number\\\":\\\"411111**********\\\",\\\"card_holder_name\\\":null,\\\"card_expiry_date\\\":\\\"*** i32 ***\\\",\\\"card_cvc\\\":\\\"*** alloc::string::String ***\\\",\\\"flexible_3d\\\":null,\\\"moto\\\":null,\\\"term_url\\\":null},\\\"delivery\\\":{\\\"first_name\\\":\\\"*** alloc::string::String ***\\\",\\\"last_name\\\":\\\"*** alloc::string::String ***\\\",\\\"address1\\\":\\\"*** alloc::string::String ***\\\",\\\"house_number\\\":\\\"*** alloc::string::String ***\\\",\\\"zip_code\\\":\\\"*** alloc::string::String ***\\\",\\\"city\\\":\\\"San Fransico\\\",\\\"country\\\":\\\"US\\\"},\\\"days_active\\\":30,\\\"seconds_active\\\":259200}\",
"masked_response\":\"{\\\"success\\\":true,\\\"data\\\":{\\\"type\\\":null,\\\"order_id\\\":\\\"pay_aqRMznVMpndvmmh3IweN_1\\\",\\\"currency\\\":\\\"USD\\\",\\\"amount\\\":6540,\\\"description\\\":\\\"Its my first payment request\\\",\\\"capture\\\":null,\\\"payment_url\\\":\\\"https://testpay.multisafepay.com/customer-verification?sessionid=823HdSBIRUOQocDMYVsEILa3mj9hkmSKeRQ&type=3ds&md=2db93e2cd11234567890%2C0e728044058c4081898bbd2db93e2cd1&lang=en_US\\\",\\\"status\\\":\\\"initialized\\\",\\\"error_code\\\":null,\\\"error_info\\\":null,\\\"payment_details\\\":{\\\"account_holder_name\\\":null,\\\"account_id\\\":null,\\\"card_expiry_date\\\":\\\"*** alloc::string::String ***\\\",\\\"external_transaction_id\\\":null,\\\"last4\\\":\\\"*** alloc::string::String ***\\\",\\\"recurring_flow\\\":null,\\\"recurring_id\\\":null,\\\"recurring_model\\\":null,\\\"type\\\":\\\"VISA\\\"}}}\",\"error\":null,\"url\":\"https://testapi.multisafepay.com/v1/json/orders?api_key=86c095c1595b4b5cdc4462ec9b6c35ec9302a37e\",\"method\":\"POST\",\"payment_id\":\"pay_aqRMznVMpndvmmh3IweN\",\"merchant_id\":\"merchant_1709116328\",\"created_at\":1709118709865,\"request_id\":\"018def69-d6e4-7db8-b4af-f3f9b786fc84\",\"latency\":2345,\"refund_id\":null,\"dispute_id\":null,\"status_code\":200}
```
## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
53559c22527dde9536aa493ad7cd3bf353335c1a
|
|
juspay/hyperswitch
|
juspay__hyperswitch-3864
|
Bug: feat: Add Cookie in response header
Using cookies for storing login token instead of local storage.
Add `set-cookie` response header with json-web-token as its value.
|
diff --git a/Cargo.lock b/Cargo.lock
index 2e4d3324d2e..7c7b2b9a761 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -224,7 +224,7 @@ dependencies = [
"bytes 1.5.0",
"bytestring",
"cfg-if 1.0.0",
- "cookie",
+ "cookie 0.16.2",
"derive_more",
"encoding_rs",
"futures-core",
@@ -616,7 +616,7 @@ dependencies = [
"base64 0.21.5",
"bytes 1.5.0",
"cfg-if 1.0.0",
- "cookie",
+ "cookie 0.16.2",
"derive_more",
"futures-core",
"futures-util",
@@ -1763,6 +1763,16 @@ dependencies = [
"version_check",
]
+[[package]]
+name = "cookie"
+version = "0.18.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3cd91cf61412820176e137621345ee43b3f4423e589e7ae4e50d601d93e35ef8"
+dependencies = [
+ "time",
+ "version_check",
+]
+
[[package]]
name = "cookie-factory"
version = "0.3.2"
@@ -2524,7 +2534,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65f0fbe245d714b596ba5802b46f937f5ce68dcae0f32f9a70b5c3b04d3c6f64"
dependencies = [
"base64 0.13.1",
- "cookie",
+ "cookie 0.16.2",
"futures-core",
"futures-util",
"http",
@@ -5219,6 +5229,7 @@ dependencies = [
"common_enums",
"common_utils",
"config",
+ "cookie 0.18.0",
"currency_conversion",
"data_models",
"derive_deref",
@@ -6414,7 +6425,7 @@ dependencies = [
"async-trait",
"base64 0.13.1",
"chrono",
- "cookie",
+ "cookie 0.16.2",
"fantoccini",
"futures 0.3.28",
"http",
@@ -7461,7 +7472,7 @@ checksum = "9973cb72c8587d5ad5efdb91e663d36177dc37725e6c90ca86c626b0cc45c93f"
dependencies = [
"base64 0.13.1",
"bytes 1.5.0",
- "cookie",
+ "cookie 0.16.2",
"http",
"log",
"serde",
diff --git a/crates/masking/src/maskable.rs b/crates/masking/src/maskable.rs
index 3469e1dd746..7969c9ab8e4 100644
--- a/crates/masking/src/maskable.rs
+++ b/crates/masking/src/maskable.rs
@@ -58,6 +58,24 @@ impl<T: Eq + PartialEq + Clone> Maskable<T> {
pub fn new_normal(item: T) -> Self {
Self::Normal(item)
}
+
+ ///
+ /// Checks whether the data is masked.
+ /// Returns `true` if the data is wrapped in the `Masked` variant,
+ /// returns `false` otherwise.
+ ///
+ pub fn is_masked(&self) -> bool {
+ matches!(self, Self::Masked(_))
+ }
+
+ ///
+ /// Checks whether the data is normal (not masked).
+ /// Returns `true` if the data is wrapped in the `Normal` variant,
+ /// returns `false` otherwise.
+ ///
+ pub fn is_normal(&self) -> bool {
+ matches!(self, Self::Normal(_))
+ }
}
/// Trait for providing a method on custom types for constructing `Maskable`
diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml
index 9cb7913211f..f001609ee88 100644
--- a/crates/router/Cargo.toml
+++ b/crates/router/Cargo.toml
@@ -46,6 +46,7 @@ blake3 = "1.3.3"
bytes = "1.4.0"
clap = { version = "4.3.2", default-features = false, features = ["std", "derive", "help", "usage"] }
config = { version = "0.13.3", features = ["toml"] }
+cookie = "0.18.0"
diesel = { version = "2.1.0", features = ["postgres"] }
digest = "0.9"
dyn-clone = "1.0.11"
diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs
index 26598493c87..70add106762 100644
--- a/crates/router/src/consts.rs
+++ b/crates/router/src/consts.rs
@@ -68,6 +68,8 @@ 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 JWT_TOKEN_COOKIE_NAME: &str = "login_token";
+
pub const USER_BLACKLIST_PREFIX: &str = "BU_";
pub const ROLE_BLACKLIST_PREFIX: &str = "BR_";
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index 3cb11d1c0e9..9dd7df66fa6 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -5,6 +5,7 @@ use common_enums::RequestIncrementalAuthorization;
use common_utils::{consts::X_HS_LATENCY, fp_utils};
use diesel_models::ephemeral_key;
use error_stack::{report, IntoReport, ResultExt};
+use masking::Maskable;
use router_env::{instrument, tracing};
use super::{flows::Feature, PaymentData};
@@ -466,20 +467,25 @@ where
.map(|status_code| {
vec![(
"connector_http_status_code".to_string(),
- status_code.to_string(),
+ Maskable::new_normal(status_code.to_string()),
)]
})
.unwrap_or_default();
if let Some(payment_confirm_source) = payment_intent.payment_confirm_source {
headers.push((
"payment_confirm_source".to_string(),
- payment_confirm_source.to_string(),
+ Maskable::new_normal(payment_confirm_source.to_string()),
))
}
headers.extend(
external_latency
- .map(|latency| vec![(X_HS_LATENCY.to_string(), latency.to_string())])
+ .map(|latency| {
+ vec![(
+ X_HS_LATENCY.to_string(),
+ Maskable::new_normal(latency.to_string()),
+ )]
+ })
.unwrap_or_default(),
);
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index c1e10ddfabf..703c6443160 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -93,12 +93,13 @@ pub async fn signup(
UserStatus::Active,
)
.await?;
- let token = utils::user::generate_jwt_auth_token(&state, &user_from_db, &user_role).await?;
utils::user_role::set_role_permissions_in_cache_by_user_role(&state, &user_role).await;
- Ok(ApplicationResponse::Json(
- utils::user::get_dashboard_entry_response(&state, user_from_db, user_role, token)?,
- ))
+ 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, user_role, token.clone())?;
+
+ auth::cookies::set_cookie_response(response, token)
}
pub async fn signin_without_invite_checks(
@@ -121,12 +122,12 @@ pub async fn signin_without_invite_checks(
user_from_db.compare_password(request.password)?;
let user_role = user_from_db.get_role_from_db(state.clone()).await?;
- let token = utils::user::generate_jwt_auth_token(&state, &user_from_db, &user_role).await?;
utils::user_role::set_role_permissions_in_cache_by_user_role(&state, &user_role).await;
- Ok(ApplicationResponse::Json(
- utils::user::get_dashboard_entry_response(&state, user_from_db, user_role, token)?,
- ))
+ 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, user_role, token.clone())?;
+ auth::cookies::set_cookie_response(response, token)
}
pub async fn signin(
@@ -168,9 +169,9 @@ pub async fn signin(
.await?
};
- Ok(ApplicationResponse::Json(
- signin_strategy.get_signin_response(&state).await?,
- ))
+ let response = signin_strategy.get_signin_response(&state).await?;
+ let token = utils::user::get_token_from_signin_response(&response);
+ auth::cookies::set_cookie_response(response, token)
}
#[cfg(feature = "email")]
@@ -271,7 +272,7 @@ pub async fn connect_account(
pub async fn signout(state: AppState, user_from_token: auth::UserFromToken) -> UserResponse<()> {
auth::blacklist::insert_user_in_blacklist(&state, &user_from_token.user_id).await?;
- Ok(ApplicationResponse::StatusOk)
+ auth::cookies::remove_cookie_response()
}
pub async fn change_password(
@@ -971,14 +972,14 @@ pub async fn accept_invite_from_email(
utils::user_role::set_role_permissions_in_cache_by_user_role(&state, &update_status_result)
.await;
- Ok(ApplicationResponse::Json(
- utils::user::get_dashboard_entry_response(
- &state,
- user_from_db,
- update_status_result,
- token,
- )?,
- ))
+ let response = utils::user::get_dashboard_entry_response(
+ &state,
+ user_from_db,
+ update_status_result,
+ token.clone(),
+ )?;
+
+ auth::cookies::set_cookie_response(response, token)
}
pub async fn create_internal_user(
@@ -1130,17 +1131,17 @@ pub async fn switch_merchant_id(
(token, user_role.role_id.clone())
};
- Ok(ApplicationResponse::Json(
- user_api::DashboardEntryResponse {
- token,
- name: user.get_name(),
- email: user.get_email(),
- user_id: user.get_user_id().to_string(),
- verification_days_left: None,
- user_role: role_id,
- merchant_id: request.merchant_id,
- },
- ))
+ let response = user_api::DashboardEntryResponse {
+ token: token.clone(),
+ name: user.get_name(),
+ email: user.get_email(),
+ user_id: user.get_user_id().to_string(),
+ verification_days_left: None,
+ user_role: role_id,
+ merchant_id: request.merchant_id,
+ };
+
+ auth::cookies::set_cookie_response(response, token)
}
pub async fn create_merchant_account(
@@ -1318,9 +1319,10 @@ pub async fn verify_email_without_invite_checks(
let token = utils::user::generate_jwt_auth_token(&state, &user_from_db, &user_role).await?;
utils::user_role::set_role_permissions_in_cache_by_user_role(&state, &user_role).await;
- Ok(ApplicationResponse::Json(
- utils::user::get_dashboard_entry_response(&state, user_from_db, user_role, token)?,
- ))
+ let response =
+ utils::user::get_dashboard_entry_response(&state, user_from_db, user_role, token.clone())?;
+
+ auth::cookies::set_cookie_response(response, token)
}
#[cfg(feature = "email")]
@@ -1373,9 +1375,9 @@ pub async fn verify_email(
.await
.map_err(|e| logger::error!(?e));
- Ok(ApplicationResponse::Json(
- signin_strategy.get_signin_response(&state).await?,
- ))
+ let response = signin_strategy.get_signin_response(&state).await?;
+ let token = utils::user::get_token_from_signin_response(&response);
+ auth::cookies::set_cookie_response(response, token)
}
#[cfg(feature = "email")]
diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs
index b81b980c07a..587e0e04435 100644
--- a/crates/router/src/core/user_role.rs
+++ b/crates/router/src/core/user_role.rs
@@ -158,12 +158,13 @@ pub async fn transfer_org_ownership(
.await
.to_not_found_response(UserErrors::InvalidRoleOperation)?;
- let token = utils::user::generate_jwt_auth_token(&state, &user_from_db, &user_role).await?;
utils::user_role::set_role_permissions_in_cache_by_user_role(&state, &user_role).await;
- Ok(ApplicationResponse::Json(
- utils::user::get_dashboard_entry_response(&state, user_from_db, user_role, token)?,
- ))
+ 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, user_role, token.clone())?;
+
+ auth::cookies::set_cookie_response(response, token)
}
pub async fn accept_invitation(
@@ -202,12 +203,17 @@ pub async fn accept_invitation(
.change_context(UserErrors::InternalServerError)?
.into();
- let token = utils::user::generate_jwt_auth_token(&state, &user_from_db, &user_role).await?;
utils::user_role::set_role_permissions_in_cache_by_user_role(&state, &user_role).await;
- return Ok(ApplicationResponse::Json(
- utils::user::get_dashboard_entry_response(&state, user_from_db, user_role, token)?,
- ));
+ 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,
+ user_role,
+ token.clone(),
+ )?;
+ return auth::cookies::set_cookie_response(response, token);
}
Ok(ApplicationResponse::StatusOk)
diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs
index bc8e3b99d23..00558e6c4f4 100644
--- a/crates/router/src/services/api.rs
+++ b/crates/router/src/services/api.rs
@@ -9,7 +9,10 @@ use std::{
time::{Duration, Instant},
};
-use actix_web::{body, web, FromRequest, HttpRequest, HttpResponse, Responder, ResponseError};
+use actix_web::{
+ body, http::header::HeaderValue, web, FromRequest, HttpRequest, HttpResponse, Responder,
+ ResponseError,
+};
use api_models::enums::{CaptureMethod, PaymentMethodType};
pub use client::{proxy_bypass_urls, ApiClient, MockApiClient, ProxyClient};
use common_enums::Currency;
@@ -20,7 +23,7 @@ use common_utils::{
request::RequestContent,
};
use error_stack::{report, IntoReport, Report, ResultExt};
-use masking::{PeekInterface, Secret};
+use masking::{Maskable, PeekInterface, Secret};
use router_env::{instrument, tracing, tracing_actix_web::RequestId, Tag};
use serde::Serialize;
use serde_json::json;
@@ -110,7 +113,7 @@ pub trait ConnectorIntegration<T, Req, Resp>: ConnectorIntegrationAny<T, Req, Re
&self,
_req: &types::RouterData<T, Req, Resp>,
_connectors: &Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
Ok(vec![])
}
@@ -847,7 +850,7 @@ pub enum ApplicationResponse<R> {
Form(Box<RedirectionFormData>),
PaymentLinkForm(Box<PaymentLinkAction>),
FileData((Vec<u8>, mime::Mime)),
- JsonWithHeaders((R, Vec<(String, String)>)),
+ JsonWithHeaders((R, Vec<(String, Maskable<String>)>)),
}
#[derive(Debug, Eq, PartialEq)]
@@ -1046,7 +1049,7 @@ where
);
if let Some((_, value)) = headers.iter().find(|(key, _)| key == X_HS_LATENCY) {
- if let Ok(external_latency) = value.parse::<u128>() {
+ if let Ok(external_latency) = value.clone().into_inner().parse::<u128>() {
overhead_latency.replace(external_latency);
}
}
@@ -1126,7 +1129,7 @@ where
let incoming_request_header = request.headers();
- let incoming_header_to_log: HashMap<String, http::header::HeaderValue> =
+ let incoming_header_to_log: HashMap<String, HeaderValue> =
incoming_request_header
.iter()
.fold(HashMap::new(), |mut acc, (key, value)| {
@@ -1333,21 +1336,33 @@ pub fn http_server_error_json_response<T: body::MessageBody + 'static>(
pub fn http_response_json_with_headers<T: body::MessageBody + 'static>(
response: T,
- mut headers: Vec<(String, String)>,
+ headers: Vec<(String, Maskable<String>)>,
request_duration: Option<Duration>,
) -> HttpResponse {
let mut response_builder = HttpResponse::Ok();
-
- for (name, value) in headers.iter_mut() {
- if name == X_HS_LATENCY {
+ for (header_name, header_value) in headers {
+ let is_sensitive_header = header_value.is_masked();
+ let mut header_value = header_value.into_inner();
+ if header_name == X_HS_LATENCY {
if let Some(request_duration) = request_duration {
- if let Ok(external_latency) = value.parse::<u128>() {
+ if let Ok(external_latency) = header_value.parse::<u128>() {
let updated_duration = request_duration.as_millis() - external_latency;
- *value = updated_duration.to_string();
+ header_value = updated_duration.to_string();
}
}
}
- response_builder.append_header((name.clone(), value.clone()));
+ let mut header_value = match HeaderValue::from_str(header_value.as_str()) {
+ Ok(header_value) => header_value,
+ Err(e) => {
+ logger::error!(?e);
+ return http_server_error_json_response("Something Went Wrong");
+ }
+ };
+
+ if is_sensitive_header {
+ header_value.set_sensitive(true);
+ }
+ response_builder.append_header((header_name, header_value));
}
response_builder
diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs
index 7cf1855b441..eb115f5701c 100644
--- a/crates/router/src/services/authentication.rs
+++ b/crates/router/src/services/authentication.rs
@@ -33,6 +33,8 @@ use crate::{
utils::OptionExt,
};
pub mod blacklist;
+#[cfg(feature = "olap")]
+pub mod cookies;
#[derive(Clone, Debug)]
pub struct AuthenticationData {
diff --git a/crates/router/src/services/authentication/cookies.rs b/crates/router/src/services/authentication/cookies.rs
new file mode 100644
index 00000000000..d7fc4c10315
--- /dev/null
+++ b/crates/router/src/services/authentication/cookies.rs
@@ -0,0 +1,62 @@
+use cookie::{
+ time::{Duration, OffsetDateTime},
+ Cookie, SameSite,
+};
+use masking::{ExposeInterface, Mask, Secret};
+
+use crate::{
+ consts::{JWT_TOKEN_COOKIE_NAME, JWT_TOKEN_TIME_IN_SECS},
+ core::errors::{UserErrors, UserResponse},
+ services::ApplicationResponse,
+};
+
+pub fn set_cookie_response<R>(response: R, token: Secret<String>) -> UserResponse<R> {
+ let jwt_expiry_in_seconds = JWT_TOKEN_TIME_IN_SECS
+ .try_into()
+ .map_err(|_| UserErrors::InternalServerError)?;
+ let (expiry, max_age) = get_expiry_and_max_age_from_seconds(jwt_expiry_in_seconds);
+
+ let header_value = create_cookie(token, expiry, max_age)
+ .to_string()
+ .into_masked();
+ let header_key = get_cookie_header();
+ let header = vec![(header_key, header_value)];
+
+ Ok(ApplicationResponse::JsonWithHeaders((response, header)))
+}
+
+pub fn remove_cookie_response() -> UserResponse<()> {
+ let (expiry, max_age) = get_expiry_and_max_age_from_seconds(0);
+
+ let header_key = get_cookie_header();
+ let header_value = create_cookie("".to_string().into(), expiry, max_age)
+ .to_string()
+ .into_masked();
+ let header = vec![(header_key, header_value)];
+ Ok(ApplicationResponse::JsonWithHeaders(((), header)))
+}
+
+fn create_cookie<'c>(
+ token: Secret<String>,
+ expires: OffsetDateTime,
+ max_age: Duration,
+) -> Cookie<'c> {
+ Cookie::build((JWT_TOKEN_COOKIE_NAME, token.expose()))
+ .http_only(true)
+ .secure(true)
+ .same_site(SameSite::Strict)
+ .path("/")
+ .expires(expires)
+ .max_age(max_age)
+ .build()
+}
+
+fn get_expiry_and_max_age_from_seconds(seconds: i64) -> (OffsetDateTime, Duration) {
+ let max_age = Duration::seconds(seconds);
+ let expiry = OffsetDateTime::now_utc().saturating_add(max_age);
+ (expiry, max_age)
+}
+
+fn get_cookie_header() -> String {
+ actix_http::header::SET_COOKIE.to_string()
+}
diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs
index cfab331f148..e97d5ae1efd 100644
--- a/crates/router/src/utils/user.rs
+++ b/crates/router/src/utils/user.rs
@@ -170,3 +170,10 @@ pub async fn get_user_from_db_by_email(
.await
.map(UserFromStorage::from)
}
+
+pub fn get_token_from_signin_response(resp: &user_api::SignInResponse) -> Secret<String> {
+ match resp {
+ user_api::SignInResponse::DashboardEntry(data) => data.token.clone(),
+ user_api::SignInResponse::MerchantSelect(data) => data.token.clone(),
+ }
+}
|
2024-02-28T09:45:16Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [X] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
This is the first PR for cookie implementation.
In this pr, `set-cookie` header has been added to response header, where value of the header is jwt.
<!-- Describe your changes in detail -->
### 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
Storing JWT in cookies instead of local storage
<!--
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?
Following apis should have `set-cookie` header with jwt as value.
```
curl --location '<URL>/user/signup' \
--header 'Content-Type: application/json' \
--data-raw '{
"email": "email",
"password": "password"
}'
```
```
curl --location '<URL>/user/v2/signin' \
--header 'Content-Type: application/json' \
--data-raw '{
"email": "email",
"password": "password"
}'
```
```
curl --location '<URL>/user/signin' \
--header 'Content-Type: application/json' \
--data-raw '{
"email": "email",
"password": "password"
}'
```
```
curl --location '<URL>/user/verify_email' \
--header 'Content-Type: application/json' \
--data '{
"token": "email token"
}'
```
```
curl --location '<URL>/user/v2/verify_email' \
--header 'Content-Type: application/json' \
--data '{
"token": "email token"
}'
```
```
curl --location '<URL>/user/accept_invite_from_email' \
--header 'Content-Type: application/json' \
--data '{
"token": "email token"
}'
```
```
curl --location '<URL>/user/switch_merchant' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer <JWT>' \
--data '{
"merchant_id": "merchant_1707460394"
}'
```
```
curl --location '<URL>/user/user/transfer_ownership' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer <JWT>' \
--data-raw '{
"email": "email"
}'
```
```
curl --location '<URL>/user/user/invite/accept' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer <JWT>' \
--data '{
"merchant_ids": [
"merchant_1705922092",
"merchant_1705414514"
],
"need_dashboard_entry_response": true
}'
```
Following api should have `set-cookie` header with `""` (empty value) as value.
```
curl --location '<URL>/user/signout' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer <JWT>' \
--data-raw '{
"email": "email"
}'
```
<!--
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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
e1b894770f3d37c2a255d3cec1d58ec71ba29c78
|
|
juspay/hyperswitch
|
juspay__hyperswitch-3855
|
Bug: [FEATURE] : [Mollie] mask pii information in connector request and response
### Feature Description
Mask pii information passed and received in the connector request and response
### Possible Implementation
Refactor all sensitive response and request fields secret
### 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/mollie/transformers.rs b/crates/router/src/connector/mollie/transformers.rs
index af1159cd2c3..be4691341b8 100644
--- a/crates/router/src/connector/mollie/transformers.rs
+++ b/crates/router/src/connector/mollie/transformers.rs
@@ -64,7 +64,7 @@ pub struct MolliePaymentsRequest {
payment_method_data: PaymentMethodData,
metadata: Option<MollieMetadata>,
sequence_type: SequenceType,
- mandate_id: Option<String>,
+ mandate_id: Option<Secret<String>>,
}
#[derive(Default, Debug, Serialize, Deserialize)]
@@ -92,7 +92,7 @@ pub enum PaymentMethodData {
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ApplePayMethodData {
- apple_pay_payment_token: String,
+ apple_pay_payment_token: Secret<String>,
}
#[derive(Debug, Serialize)]
@@ -333,7 +333,7 @@ fn get_payment_method_for_wallet(
}
api_models::payments::WalletData::ApplePay(applepay_wallet_data) => {
Ok(PaymentMethodData::Applepay(Box::new(ApplePayMethodData {
- apple_pay_payment_token: applepay_wallet_data.payment_data.to_owned(),
+ apple_pay_payment_token: Secret::new(applepay_wallet_data.payment_data.to_owned()),
})))
}
_ => Err(errors::ConnectorError::NotImplemented(
@@ -451,16 +451,16 @@ pub struct Links {
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CardDetails {
- pub card_number: String,
- pub card_holder: String,
- pub card_expiry_date: String,
- pub card_cvv: String,
+ pub card_number: Secret<String>,
+ pub card_holder: Secret<String>,
+ pub card_expiry_date: Secret<String>,
+ pub card_cvv: Secret<String>,
}
#[derive(Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct BankDetails {
- billing_email: String,
+ billing_email: Email,
}
pub struct MollieAuthType {
|
2024-02-27T13:26:38Z
|
## 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 -->
Mask pii information passed and received in the connector request and response for Mollie.
## Test Case
<!--
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 an Apple pay payment
2. Check if `apple_pay_payment_token` in the `masked_response` is masked
```
curl --location '{{base_url}}/analytics/v1/connector_event_logs?type=Payment&payment_id={{payment_id}}' \
--header 'sec-ch-ua: "Not A(Brand";v="99", "Google Chrome";v="121", "Chromium";v="121"' \
--header 'sec-ch-ua-mobile: ?0' \
--header 'authorization: Bearer JWT_token' \
--header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36' \
--header 'Content-Type: application/json' \
--header 'Referer: https://integ.hyperswitch.io/' \
--header 'api-key: {{api-key}}' \
--header 'sec-ch-ua-platform: "macOS"'
```
## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
fbe9d2f19e9c0ca3af45a60e3d82b3ea774e11ce
|
|
juspay/hyperswitch
|
juspay__hyperswitch-3853
|
Bug: [FEATURE] : [Klarna] mask pii information in connector request and response
### Feature Description
Mask pii information passed and received in the connector request and response
### Possible Implementation
Refactor all sensitive response and request fields secret
### 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/klarna/transformers.rs b/crates/router/src/connector/klarna/transformers.rs
index c12f8ed1b10..29dccfbf32b 100644
--- a/crates/router/src/connector/klarna/transformers.rs
+++ b/crates/router/src/connector/klarna/transformers.rs
@@ -1,6 +1,6 @@
use api_models::payments;
use error_stack::report;
-use masking::Secret;
+use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
@@ -66,8 +66,8 @@ pub struct KlarnaSessionRequest {
#[derive(Deserialize, Serialize, Debug)]
pub struct KlarnaSessionResponse {
- pub client_token: String,
- pub session_id: String,
+ pub client_token: Secret<String>,
+ pub session_id: Secret<String>,
}
impl TryFrom<&types::PaymentsSessionRouterData> for KlarnaSessionRequest {
@@ -110,8 +110,8 @@ impl TryFrom<types::PaymentsSessionResponseRouterData<KlarnaSessionResponse>>
response: Ok(types::PaymentsResponseData::SessionResponse {
session_token: types::api::SessionToken::Klarna(Box::new(
payments::KlarnaSessionTokenResponse {
- session_token: response.client_token.clone(),
- session_id: response.session_id.clone(),
+ session_token: response.client_token.clone().expose(),
+ session_id: response.session_id.clone().expose(),
},
)),
}),
|
2024-02-27T13:00:03Z
|
## 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 -->
Mask pii information passed and received in the connector request and response for Klarna.
## Test Cases
<!--
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 Klarna payment with Klarna connector. Set payment experience as invoke SDK.
_Note: As it requires invoking SDK, can't be tested from local_
## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
3e13fb908adf84974312c4785cb4ce57e46a496f
|
|
juspay/hyperswitch
|
juspay__hyperswitch-3867
|
Bug: [Analytics]/[Dispute] Create API's endpoints for disputes analytics
These are the metrics needed
- Number of disputes
- disputes challenged
- disputes won
- disputes lost
- Total amount disputed
- Total dispute lost amount
## Filters
## Group By Dimensions
|
diff --git a/crates/analytics/src/clickhouse.rs b/crates/analytics/src/clickhouse.rs
index fed029f2edb..6ebac7c1d92 100644
--- a/crates/analytics/src/clickhouse.rs
+++ b/crates/analytics/src/clickhouse.rs
@@ -23,7 +23,7 @@ use crate::{
metrics::{latency::LatencyAvg, ApiEventMetricRow},
},
connector_events::events::ConnectorEventsResult,
- disputes::filters::DisputeFilterRow,
+ disputes::{filters::DisputeFilterRow, metrics::DisputeMetricRow},
outgoing_webhook_event::events::OutgoingWebhookLogsResult,
sdk_events::events::SdkEventsResult,
types::TableEngine,
@@ -170,6 +170,7 @@ impl super::outgoing_webhook_event::events::OutgoingWebhookLogsFilterAnalytics
{
}
impl super::disputes::filters::DisputeFilterAnalytics for ClickhouseClient {}
+impl super::disputes::metrics::DisputeMetricAnalytics for ClickhouseClient {}
#[derive(Debug, serde::Serialize)]
struct CkhQuery {
@@ -278,6 +279,17 @@ impl TryInto<RefundFilterRow> for serde_json::Value {
))
}
}
+impl TryInto<DisputeMetricRow> for serde_json::Value {
+ type Error = Report<ParsingError>;
+
+ fn try_into(self) -> Result<DisputeMetricRow, Self::Error> {
+ serde_json::from_value(self)
+ .into_report()
+ .change_context(ParsingError::StructParseFailure(
+ "Failed to parse DisputeMetricRow in clickhouse results",
+ ))
+ }
+}
impl TryInto<DisputeFilterRow> for serde_json::Value {
type Error = Report<ParsingError>;
diff --git a/crates/analytics/src/disputes.rs b/crates/analytics/src/disputes.rs
index b6d7e6280c7..8cf1b3db0fd 100644
--- a/crates/analytics/src/disputes.rs
+++ b/crates/analytics/src/disputes.rs
@@ -1,5 +1,9 @@
+pub mod accumulators;
mod core;
-
pub mod filters;
+pub mod metrics;
+pub mod types;
+pub use accumulators::{DisputeMetricAccumulator, DisputeMetricsAccumulator};
-pub use self::core::get_filters;
+pub trait DisputeAnalytics: metrics::DisputeMetricAnalytics {}
+pub use self::core::{get_filters, get_metrics};
diff --git a/crates/analytics/src/disputes/accumulators.rs b/crates/analytics/src/disputes/accumulators.rs
new file mode 100644
index 00000000000..1997d75d323
--- /dev/null
+++ b/crates/analytics/src/disputes/accumulators.rs
@@ -0,0 +1,100 @@
+use api_models::analytics::disputes::DisputeMetricsBucketValue;
+use diesel_models::enums as storage_enums;
+
+use super::metrics::DisputeMetricRow;
+#[derive(Debug, Default)]
+pub struct DisputeMetricsAccumulator {
+ pub disputes_status_rate: RateAccumulator,
+ pub total_amount_disputed: SumAccumulator,
+ pub total_dispute_lost_amount: SumAccumulator,
+}
+#[derive(Debug, Default)]
+pub struct RateAccumulator {
+ pub won_count: i64,
+ pub challenged_count: i64,
+ pub lost_count: i64,
+ pub total: i64,
+}
+#[derive(Debug, Default)]
+#[repr(transparent)]
+pub struct SumAccumulator {
+ pub total: Option<i64>,
+}
+
+pub trait DisputeMetricAccumulator {
+ type MetricOutput;
+
+ fn add_metrics_bucket(&mut self, metrics: &DisputeMetricRow);
+
+ fn collect(self) -> Self::MetricOutput;
+}
+
+impl DisputeMetricAccumulator for SumAccumulator {
+ type MetricOutput = Option<u64>;
+ #[inline]
+ fn add_metrics_bucket(&mut self, metrics: &DisputeMetricRow) {
+ self.total = match (
+ self.total,
+ metrics
+ .total
+ .as_ref()
+ .and_then(bigdecimal::ToPrimitive::to_i64),
+ ) {
+ (None, None) => None,
+ (None, i @ Some(_)) | (i @ Some(_), None) => i,
+ (Some(a), Some(b)) => Some(a + b),
+ }
+ }
+ #[inline]
+ fn collect(self) -> Self::MetricOutput {
+ self.total.and_then(|i| u64::try_from(i).ok())
+ }
+}
+
+impl DisputeMetricAccumulator for RateAccumulator {
+ type MetricOutput = Option<(Option<u64>, Option<u64>, Option<u64>, Option<u64>)>;
+
+ fn add_metrics_bucket(&mut self, metrics: &DisputeMetricRow) {
+ if let Some(ref dispute_status) = metrics.dispute_status {
+ if dispute_status.as_ref() == &storage_enums::DisputeStatus::DisputeChallenged {
+ self.challenged_count += metrics.count.unwrap_or_default();
+ }
+ if dispute_status.as_ref() == &storage_enums::DisputeStatus::DisputeWon {
+ self.won_count += metrics.count.unwrap_or_default();
+ }
+ if dispute_status.as_ref() == &storage_enums::DisputeStatus::DisputeLost {
+ self.lost_count += metrics.count.unwrap_or_default();
+ }
+ };
+
+ self.total += metrics.count.unwrap_or_default();
+ }
+
+ fn collect(self) -> Self::MetricOutput {
+ if self.total <= 0 {
+ Some((None, None, None, None))
+ } else {
+ Some((
+ u64::try_from(self.challenged_count).ok(),
+ u64::try_from(self.won_count).ok(),
+ u64::try_from(self.lost_count).ok(),
+ u64::try_from(self.total).ok(),
+ ))
+ }
+ }
+}
+
+impl DisputeMetricsAccumulator {
+ pub fn collect(self) -> DisputeMetricsBucketValue {
+ let (challenge_rate, won_rate, lost_rate, total_dispute) =
+ self.disputes_status_rate.collect().unwrap_or_default();
+ DisputeMetricsBucketValue {
+ disputes_challenged: challenge_rate,
+ disputes_won: won_rate,
+ disputes_lost: lost_rate,
+ total_amount_disputed: self.total_amount_disputed.collect(),
+ total_dispute_lost_amount: self.total_dispute_lost_amount.collect(),
+ total_dispute,
+ }
+ }
+}
diff --git a/crates/analytics/src/disputes/core.rs b/crates/analytics/src/disputes/core.rs
index 8ccbbdea6d2..ae013aa81d1 100644
--- a/crates/analytics/src/disputes/core.rs
+++ b/crates/analytics/src/disputes/core.rs
@@ -1,15 +1,125 @@
+use std::collections::HashMap;
+
use api_models::analytics::{
- disputes::DisputeDimensions, DisputeFilterValue, DisputeFiltersResponse,
- GetDisputeFilterRequest,
+ disputes::{
+ DisputeDimensions, DisputeMetrics, DisputeMetricsBucketIdentifier,
+ DisputeMetricsBucketResponse,
+ },
+ AnalyticsMetadata, DisputeFilterValue, DisputeFiltersResponse, GetDisputeFilterRequest,
+ GetDisputeMetricRequest, MetricsResponse,
+};
+use error_stack::{IntoReport, ResultExt};
+use router_env::{
+ logger,
+ tracing::{self, Instrument},
};
-use error_stack::ResultExt;
-use super::filters::{get_dispute_filter_for_dimension, DisputeFilterRow};
+use super::{
+ filters::{get_dispute_filter_for_dimension, DisputeFilterRow},
+ DisputeMetricsAccumulator,
+};
use crate::{
+ disputes::DisputeMetricAccumulator,
errors::{AnalyticsError, AnalyticsResult},
- AnalyticsProvider,
+ metrics, AnalyticsProvider,
};
+pub async fn get_metrics(
+ pool: &AnalyticsProvider,
+ merchant_id: &String,
+ req: GetDisputeMetricRequest,
+) -> AnalyticsResult<MetricsResponse<DisputeMetricsBucketResponse>> {
+ let mut metrics_accumulator: HashMap<
+ DisputeMetricsBucketIdentifier,
+ DisputeMetricsAccumulator,
+ > = 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_dispute_query",
+ refund_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_dispute_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()
+ .into_report()
+ .change_context(AnalyticsError::UnknownError)?
+ {
+ let data = data?;
+ let attributes = &[
+ metrics::request::add_attributes("metric_type", metric.to_string()),
+ metrics::request::add_attributes("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 {
+ DisputeMetrics::DisputeStatusMetric => metrics_builder
+ .disputes_status_rate
+ .add_metrics_bucket(&value),
+ DisputeMetrics::TotalAmountDisputed => metrics_builder
+ .total_amount_disputed
+ .add_metrics_bucket(&value),
+ DisputeMetrics::TotalDisputeLostAmount => metrics_builder
+ .total_dispute_lost_amount
+ .add_metrics_bucket(&value),
+ }
+ }
+
+ logger::debug!(
+ "Analytics Accumulated Results: metric: {}, results: {:#?}",
+ metric,
+ metrics_accumulator
+ );
+ }
+ let query_data: Vec<DisputeMetricsBucketResponse> = metrics_accumulator
+ .into_iter()
+ .map(|(id, val)| DisputeMetricsBucketResponse {
+ 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: GetDisputeFilterRequest,
@@ -76,9 +186,7 @@ pub async fn get_filters(
.change_context(AnalyticsError::UnknownError)?
.into_iter()
.filter_map(|fil: DisputeFilterRow| match dim {
- DisputeDimensions::DisputeStatus => fil.dispute_status,
DisputeDimensions::DisputeStage => fil.dispute_stage,
- DisputeDimensions::ConnectorStatus => fil.connector_status,
DisputeDimensions::Connector => fil.connector,
})
.collect::<Vec<String>>();
diff --git a/crates/analytics/src/disputes/metrics.rs b/crates/analytics/src/disputes/metrics.rs
new file mode 100644
index 00000000000..4963626d0fa
--- /dev/null
+++ b/crates/analytics/src/disputes/metrics.rs
@@ -0,0 +1,119 @@
+mod dispute_status_metric;
+mod total_amount_disputed;
+mod total_dispute_lost_amount;
+
+use api_models::{
+ analytics::{
+ disputes::{
+ DisputeDimensions, DisputeFilters, DisputeMetrics, DisputeMetricsBucketIdentifier,
+ },
+ Granularity,
+ },
+ payments::TimeRange,
+};
+use diesel_models::enums as storage_enums;
+use time::PrimitiveDateTime;
+
+use self::{
+ dispute_status_metric::DisputeStatusMetric, total_amount_disputed::TotalAmountDisputed,
+ total_dispute_lost_amount::TotalDisputeLostAmount,
+};
+use crate::{
+ query::{Aggregate, GroupByClause, ToSql, Window},
+ types::{AnalyticsCollection, AnalyticsDataSource, DBEnumWrapper, LoadRow, MetricsResult},
+};
+#[derive(Debug, Eq, PartialEq, serde::Deserialize)]
+pub struct DisputeMetricRow {
+ pub dispute_stage: Option<DBEnumWrapper<storage_enums::DisputeStage>>,
+ pub dispute_status: Option<DBEnumWrapper<storage_enums::DisputeStatus>>,
+ pub connector: Option<String>,
+ 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 DisputeMetricAnalytics: LoadRow<DisputeMetricRow> {}
+
+#[async_trait::async_trait]
+pub trait DisputeMetric<T>
+where
+ T: AnalyticsDataSource + DisputeMetricAnalytics,
+ 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: &[DisputeDimensions],
+ merchant_id: &str,
+ filters: &DisputeFilters,
+ granularity: &Option<Granularity>,
+ time_range: &TimeRange,
+ pool: &T,
+ ) -> MetricsResult<Vec<(DisputeMetricsBucketIdentifier, DisputeMetricRow)>>;
+}
+
+#[async_trait::async_trait]
+impl<T> DisputeMetric<T> for DisputeMetrics
+where
+ T: AnalyticsDataSource + DisputeMetricAnalytics,
+ 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: &[DisputeDimensions],
+ merchant_id: &str,
+ filters: &DisputeFilters,
+ granularity: &Option<Granularity>,
+ time_range: &TimeRange,
+ pool: &T,
+ ) -> MetricsResult<Vec<(DisputeMetricsBucketIdentifier, DisputeMetricRow)>> {
+ match self {
+ Self::TotalAmountDisputed => {
+ TotalAmountDisputed::default()
+ .load_metrics(
+ dimensions,
+ merchant_id,
+ filters,
+ granularity,
+ time_range,
+ pool,
+ )
+ .await
+ }
+ Self::DisputeStatusMetric => {
+ DisputeStatusMetric::default()
+ .load_metrics(
+ dimensions,
+ merchant_id,
+ filters,
+ granularity,
+ time_range,
+ pool,
+ )
+ .await
+ }
+ Self::TotalDisputeLostAmount => {
+ TotalDisputeLostAmount::default()
+ .load_metrics(
+ dimensions,
+ merchant_id,
+ filters,
+ granularity,
+ time_range,
+ pool,
+ )
+ .await
+ }
+ }
+ }
+}
diff --git a/crates/analytics/src/disputes/metrics/dispute_status_metric.rs b/crates/analytics/src/disputes/metrics/dispute_status_metric.rs
new file mode 100644
index 00000000000..5b97021becc
--- /dev/null
+++ b/crates/analytics/src/disputes/metrics/dispute_status_metric.rs
@@ -0,0 +1,119 @@
+use api_models::analytics::{
+ disputes::{DisputeDimensions, DisputeFilters, DisputeMetricsBucketIdentifier},
+ Granularity, TimeRange,
+};
+use common_utils::errors::ReportSwitchExt;
+use error_stack::ResultExt;
+use time::PrimitiveDateTime;
+
+use super::DisputeMetricRow;
+use crate::{
+ query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window},
+ types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
+};
+#[derive(Default)]
+pub(super) struct DisputeStatusMetric {}
+
+#[async_trait::async_trait]
+impl<T> super::DisputeMetric<T> for DisputeStatusMetric
+where
+ T: AnalyticsDataSource + super::DisputeMetricAnalytics,
+ 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: &[DisputeDimensions],
+ merchant_id: &str,
+ filters: &DisputeFilters,
+ granularity: &Option<Granularity>,
+ time_range: &TimeRange,
+ pool: &T,
+ ) -> MetricsResult<Vec<(DisputeMetricsBucketIdentifier, DisputeMetricRow)>>
+ where
+ T: AnalyticsDataSource + super::DisputeMetricAnalytics,
+ {
+ let mut query_builder = QueryBuilder::new(AnalyticsCollection::Dispute);
+
+ for dim in dimensions {
+ query_builder.add_select_column(dim).switch()?;
+ }
+
+ query_builder.add_select_column("dispute_status").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 {
+ query_builder.add_group_by_clause(dim).switch()?;
+ }
+
+ query_builder
+ .add_group_by_clause("dispute_status")
+ .switch()?;
+
+ if let Some(granularity) = granularity.as_ref() {
+ granularity
+ .set_group_by_clause(&mut query_builder)
+ .switch()?;
+ }
+
+ query_builder
+ .execute_query::<DisputeMetricRow, _>(pool)
+ .await
+ .change_context(MetricsError::QueryBuildingError)?
+ .change_context(MetricsError::QueryExecutionFailure)?
+ .into_iter()
+ .map(|i| {
+ Ok((
+ DisputeMetricsBucketIdentifier::new(
+ i.dispute_stage.as_ref().map(|i| i.0),
+ i.connector.clone(),
+ 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<(DisputeMetricsBucketIdentifier, DisputeMetricRow)>,
+ crate::query::PostProcessingError,
+ >>()
+ .change_context(MetricsError::PostProcessingFailure)
+ }
+}
diff --git a/crates/analytics/src/disputes/metrics/total_amount_disputed.rs b/crates/analytics/src/disputes/metrics/total_amount_disputed.rs
new file mode 100644
index 00000000000..cbba553aa85
--- /dev/null
+++ b/crates/analytics/src/disputes/metrics/total_amount_disputed.rs
@@ -0,0 +1,116 @@
+use api_models::analytics::{
+ disputes::{DisputeDimensions, DisputeFilters, DisputeMetricsBucketIdentifier},
+ Granularity, TimeRange,
+};
+use common_utils::errors::ReportSwitchExt;
+use error_stack::ResultExt;
+use time::PrimitiveDateTime;
+
+use super::DisputeMetricRow;
+use crate::{
+ query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window},
+ types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
+};
+#[derive(Default)]
+pub(super) struct TotalAmountDisputed {}
+
+#[async_trait::async_trait]
+impl<T> super::DisputeMetric<T> for TotalAmountDisputed
+where
+ T: AnalyticsDataSource + super::DisputeMetricAnalytics,
+ 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: &[DisputeDimensions],
+ merchant_id: &str,
+ filters: &DisputeFilters,
+ granularity: &Option<Granularity>,
+ time_range: &TimeRange,
+ pool: &T,
+ ) -> MetricsResult<Vec<(DisputeMetricsBucketIdentifier, DisputeMetricRow)>>
+ where
+ T: AnalyticsDataSource + super::DisputeMetricAnalytics,
+ {
+ let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::Dispute);
+
+ for dim in dimensions {
+ query_builder.add_select_column(dim).switch()?;
+ }
+
+ query_builder
+ .add_select_column(Aggregate::Sum {
+ field: "dispute_amount",
+ alias: Some("total"),
+ })
+ .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).switch()?;
+ }
+
+ if let Some(granularity) = granularity.as_ref() {
+ granularity
+ .set_group_by_clause(&mut query_builder)
+ .switch()?;
+ }
+ query_builder
+ .add_filter_clause("dispute_status", "dispute_won")
+ .switch()?;
+
+ query_builder
+ .execute_query::<DisputeMetricRow, _>(pool)
+ .await
+ .change_context(MetricsError::QueryBuildingError)?
+ .change_context(MetricsError::QueryExecutionFailure)?
+ .into_iter()
+ .map(|i| {
+ Ok((
+ DisputeMetricsBucketIdentifier::new(
+ i.dispute_stage.as_ref().map(|i| i.0),
+ i.connector.clone(),
+ 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/disputes/metrics/total_dispute_lost_amount.rs b/crates/analytics/src/disputes/metrics/total_dispute_lost_amount.rs
new file mode 100644
index 00000000000..c7be2ab1a98
--- /dev/null
+++ b/crates/analytics/src/disputes/metrics/total_dispute_lost_amount.rs
@@ -0,0 +1,117 @@
+use api_models::analytics::{
+ disputes::{DisputeDimensions, DisputeFilters, DisputeMetricsBucketIdentifier},
+ Granularity, TimeRange,
+};
+use common_utils::errors::ReportSwitchExt;
+use error_stack::ResultExt;
+use time::PrimitiveDateTime;
+
+use super::DisputeMetricRow;
+use crate::{
+ query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window},
+ types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
+};
+#[derive(Default)]
+pub(super) struct TotalDisputeLostAmount {}
+
+#[async_trait::async_trait]
+impl<T> super::DisputeMetric<T> for TotalDisputeLostAmount
+where
+ T: AnalyticsDataSource + super::DisputeMetricAnalytics,
+ 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: &[DisputeDimensions],
+ merchant_id: &str,
+ filters: &DisputeFilters,
+ granularity: &Option<Granularity>,
+ time_range: &TimeRange,
+ pool: &T,
+ ) -> MetricsResult<Vec<(DisputeMetricsBucketIdentifier, DisputeMetricRow)>>
+ where
+ T: AnalyticsDataSource + super::DisputeMetricAnalytics,
+ {
+ let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::Dispute);
+
+ for dim in dimensions.iter() {
+ query_builder.add_select_column(dim).switch()?;
+ }
+
+ query_builder
+ .add_select_column(Aggregate::Sum {
+ field: "dispute_amount",
+ alias: Some("total"),
+ })
+ .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).switch()?;
+ }
+
+ if let Some(granularity) = granularity.as_ref() {
+ granularity
+ .set_group_by_clause(&mut query_builder)
+ .switch()?;
+ }
+
+ query_builder
+ .add_filter_clause("dispute_status", "dispute_lost")
+ .switch()?;
+
+ query_builder
+ .execute_query::<DisputeMetricRow, _>(pool)
+ .await
+ .change_context(MetricsError::QueryBuildingError)?
+ .change_context(MetricsError::QueryExecutionFailure)?
+ .into_iter()
+ .map(|i| {
+ Ok((
+ DisputeMetricsBucketIdentifier::new(
+ i.dispute_stage.as_ref().map(|i| i.0),
+ i.connector.clone(),
+ 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/disputes/types.rs b/crates/analytics/src/disputes/types.rs
new file mode 100644
index 00000000000..762e8d27554
--- /dev/null
+++ b/crates/analytics/src/disputes/types.rs
@@ -0,0 +1,29 @@
+use api_models::analytics::disputes::{DisputeDimensions, DisputeFilters};
+use error_stack::ResultExt;
+
+use crate::{
+ query::{QueryBuilder, QueryFilter, QueryResult, ToSql},
+ types::{AnalyticsCollection, AnalyticsDataSource},
+};
+
+impl<T> QueryFilter<T> for DisputeFilters
+where
+ T: AnalyticsDataSource,
+ AnalyticsCollection: ToSql<T>,
+{
+ fn set_filter_clause(&self, builder: &mut QueryBuilder<T>) -> QueryResult<()> {
+ if !self.connector.is_empty() {
+ builder
+ .add_filter_in_range_clause(DisputeDimensions::Connector, &self.connector)
+ .attach_printable("Error adding connector filter")?;
+ }
+
+ if !self.dispute_stage.is_empty() {
+ builder
+ .add_filter_in_range_clause(DisputeDimensions::DisputeStage, &self.dispute_stage)
+ .attach_printable("Error adding dispute stage filter")?;
+ }
+
+ Ok(())
+ }
+}
diff --git a/crates/analytics/src/lib.rs b/crates/analytics/src/lib.rs
index 0fb8d9eea6e..c9752bd27a6 100644
--- a/crates/analytics/src/lib.rs
+++ b/crates/analytics/src/lib.rs
@@ -15,6 +15,7 @@ pub mod sdk_events;
mod sqlx;
mod types;
use api_event::metrics::{ApiEventMetric, ApiEventMetricRow};
+use disputes::metrics::{DisputeMetric, DisputeMetricRow};
pub use types::AnalyticsDomain;
pub mod lambda_utils;
pub mod utils;
@@ -25,6 +26,7 @@ use api_models::analytics::{
api_event::{
ApiEventDimensions, ApiEventFilters, ApiEventMetrics, ApiEventMetricsBucketIdentifier,
},
+ disputes::{DisputeDimensions, DisputeFilters, DisputeMetrics, DisputeMetricsBucketIdentifier},
payments::{PaymentDimensions, PaymentFilters, PaymentMetrics, PaymentMetricsBucketIdentifier},
refunds::{RefundDimensions, RefundFilters, RefundMetrics, RefundMetricsBucketIdentifier},
sdk_events::{
@@ -393,6 +395,106 @@ impl AnalyticsProvider {
.await
}
+ pub async fn get_dispute_metrics(
+ &self,
+ metric: &DisputeMetrics,
+ dimensions: &[DisputeDimensions],
+ merchant_id: &str,
+ filters: &DisputeFilters,
+ granularity: &Option<Granularity>,
+ time_range: &TimeRange,
+ ) -> types::MetricsResult<Vec<(DisputeMetricsBucketIdentifier, DisputeMetricRow)>> {
+ // 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 disputes 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 disputes analytics metrics")
+ }
+ _ => {}
+ };
+ sqlx_result
+ }
+ }
+ },
+ &metrics::METRIC_FETCH_TIME,
+ metric,
+ self,
+ )
+ .await
+ }
+
pub async fn get_sdk_event_metrics(
&self,
metric: &SdkEventMetrics,
diff --git a/crates/analytics/src/query.rs b/crates/analytics/src/query.rs
index bc21ab8f0f4..27e4154a1a9 100644
--- a/crates/analytics/src/query.rs
+++ b/crates/analytics/src/query.rs
@@ -11,7 +11,8 @@ use api_models::{
Granularity,
},
enums::{
- AttemptStatus, AuthenticationType, Connector, Currency, PaymentMethod, PaymentMethodType,
+ AttemptStatus, AuthenticationType, Connector, Currency, DisputeStage, PaymentMethod,
+ PaymentMethodType,
},
refunds::RefundStatus,
};
@@ -363,8 +364,6 @@ impl_to_sql_for_to_string!(
PaymentDimensions,
&PaymentDistributions,
RefundDimensions,
- &DisputeDimensions,
- DisputeDimensions,
PaymentMethod,
PaymentMethodType,
AuthenticationType,
@@ -386,6 +385,8 @@ impl_to_sql_for_to_string!(&SdkEventDimensions, SdkEventDimensions, SdkEventName
impl_to_sql_for_to_string!(&ApiEventDimensions, ApiEventDimensions);
+impl_to_sql_for_to_string!(&DisputeDimensions, DisputeDimensions, DisputeStage);
+
#[derive(Debug)]
pub enum FilterTypes {
Equal,
diff --git a/crates/analytics/src/sqlx.rs b/crates/analytics/src/sqlx.rs
index 0aeffeafa9e..e88fe519c3c 100644
--- a/crates/analytics/src/sqlx.rs
+++ b/crates/analytics/src/sqlx.rs
@@ -1,6 +1,9 @@
use std::{fmt::Display, str::FromStr};
-use api_models::analytics::refunds::RefundType;
+use api_models::{
+ analytics::refunds::RefundType,
+ enums::{DisputeStage, DisputeStatus},
+};
use common_utils::errors::{CustomResult, ParsingError};
use diesel_models::enums::{
AttemptStatus, AuthenticationType, Currency, PaymentMethod, RefundStatus,
@@ -89,6 +92,8 @@ db_type!(AttemptStatus);
db_type!(PaymentMethod, TEXT);
db_type!(RefundStatus);
db_type!(RefundType);
+db_type!(DisputeStage);
+db_type!(DisputeStatus);
impl<'q, Type> Encode<'q, Postgres> for DBEnumWrapper<Type>
where
@@ -145,6 +150,7 @@ impl super::payments::distribution::PaymentDistributionAnalytics for SqlxClient
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 {}
#[async_trait::async_trait]
impl AnalyticsDataSource for SqlxClient {
@@ -454,6 +460,48 @@ impl<'a> FromRow<'a, PgRow> for super::disputes::filters::DisputeFilterRow {
})
}
}
+impl<'a> FromRow<'a, PgRow> for super::disputes::metrics::DisputeMetricRow {
+ fn from_row(row: &'a PgRow) -> sqlx::Result<Self> {
+ let dispute_stage: Option<DBEnumWrapper<DisputeStage>> =
+ row.try_get("dispute_stage").or_else(|e| match e {
+ ColumnNotFound(_) => Ok(Default::default()),
+ e => Err(e),
+ })?;
+ let dispute_status: Option<DBEnumWrapper<DisputeStatus>> =
+ row.try_get("dispute_status").or_else(|e| match e {
+ ColumnNotFound(_) => Ok(Default::default()),
+ e => Err(e),
+ })?;
+ let connector: Option<String> = row.try_get("connector").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 {
+ dispute_stage,
+ dispute_status,
+ connector,
+ total,
+ count,
+ start_bucket,
+ end_bucket,
+ })
+ }
+}
impl ToSql<SqlxClient> for PrimitiveDateTime {
fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> {
diff --git a/crates/api_models/src/analytics.rs b/crates/api_models/src/analytics.rs
index c12f8e7adfe..1434c357798 100644
--- a/crates/api_models/src/analytics.rs
+++ b/crates/api_models/src/analytics.rs
@@ -5,7 +5,7 @@ use masking::Secret;
use self::{
api_event::{ApiEventDimensions, ApiEventMetrics},
- disputes::DisputeDimensions,
+ disputes::{DisputeDimensions, DisputeMetrics},
payments::{PaymentDimensions, PaymentDistributions, PaymentMetrics},
refunds::{RefundDimensions, RefundMetrics},
sdk_events::{SdkEventDimensions, SdkEventMetrics},
@@ -271,3 +271,17 @@ pub struct DisputeFilterValue {
pub dimension: DisputeDimensions,
pub values: Vec<String>,
}
+
+#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct GetDisputeMetricRequest {
+ pub time_series: Option<TimeSeries>,
+ pub time_range: TimeRange,
+ #[serde(default)]
+ pub group_by_names: Vec<DisputeDimensions>,
+ #[serde(default)]
+ pub filters: disputes::DisputeFilters,
+ pub metrics: HashSet<DisputeMetrics>,
+ #[serde(default)]
+ pub delta: bool,
+}
diff --git a/crates/api_models/src/analytics/disputes.rs b/crates/api_models/src/analytics/disputes.rs
index 4b4b7ba3830..edb85c129e6 100644
--- a/crates/api_models/src/analytics/disputes.rs
+++ b/crates/api_models/src/analytics/disputes.rs
@@ -1,4 +1,10 @@
-use super::NameDescription;
+use std::{
+ collections::hash_map::DefaultHasher,
+ hash::{Hash, Hasher},
+};
+
+use super::{NameDescription, TimeRange};
+use crate::enums::DisputeStage;
#[derive(
Clone,
@@ -15,9 +21,7 @@ use super::NameDescription;
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum DisputeMetrics {
- DisputesChallenged,
- DisputesWon,
- DisputesLost,
+ DisputeStatusMetric,
TotalAmountDisputed,
TotalDisputeLostAmount,
}
@@ -42,8 +46,6 @@ pub enum DisputeDimensions {
// Do not change the order of these enums
// Consult the Dashboard FE folks since these also affects the order of metrics on FE
Connector,
- DisputeStatus,
- ConnectorStatus,
DisputeStage,
}
@@ -64,3 +66,70 @@ impl From<DisputeMetrics> for NameDescription {
}
}
}
+
+#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)]
+pub struct DisputeFilters {
+ #[serde(default)]
+ pub dispute_stage: Vec<DisputeStage>,
+ pub connector: Vec<String>,
+}
+
+#[derive(Debug, serde::Serialize, Eq)]
+pub struct DisputeMetricsBucketIdentifier {
+ pub dispute_stage: Option<DisputeStage>,
+ pub connector: 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 DisputeMetricsBucketIdentifier {
+ fn hash<H: Hasher>(&self, state: &mut H) {
+ self.dispute_stage.hash(state);
+ self.connector.hash(state);
+ self.time_bucket.hash(state);
+ }
+}
+impl PartialEq for DisputeMetricsBucketIdentifier {
+ 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 DisputeMetricsBucketIdentifier {
+ pub fn new(
+ dispute_stage: Option<DisputeStage>,
+ connector: Option<String>,
+ normalized_time_range: TimeRange,
+ ) -> Self {
+ Self {
+ dispute_stage,
+ connector,
+ time_bucket: normalized_time_range,
+ start_time: normalized_time_range.start_time,
+ }
+ }
+}
+
+#[derive(Debug, serde::Serialize)]
+pub struct DisputeMetricsBucketValue {
+ pub disputes_challenged: Option<u64>,
+ pub disputes_won: Option<u64>,
+ pub disputes_lost: Option<u64>,
+ pub total_amount_disputed: Option<u64>,
+ pub total_dispute_lost_amount: Option<u64>,
+ pub total_dispute: Option<u64>,
+}
+#[derive(Debug, serde::Serialize)]
+pub struct DisputeMetricsBucketResponse {
+ #[serde(flatten)]
+ pub values: DisputeMetricsBucketValue,
+ #[serde(flatten)]
+ pub dimensions: DisputeMetricsBucketIdentifier,
+}
diff --git a/crates/api_models/src/events.rs b/crates/api_models/src/events.rs
index 59b2d54016a..218881389db 100644
--- a/crates/api_models/src/events.rs
+++ b/crates/api_models/src/events.rs
@@ -97,7 +97,8 @@ impl_misc_api_event_type!(
ConnectorEventsRequest,
OutgoingWebhookLogsRequest,
GetDisputeFilterRequest,
- DisputeFiltersResponse
+ DisputeFiltersResponse,
+ GetDisputeMetricRequest
);
#[cfg(feature = "stripe")]
diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs
index 51fb6ff822b..f7bee88b8c3 100644
--- a/crates/router/src/analytics.rs
+++ b/crates/router/src/analytics.rs
@@ -9,8 +9,9 @@ pub mod routes {
};
use api_models::analytics::{
GenerateReportRequest, GetApiEventFiltersRequest, GetApiEventMetricRequest,
- GetPaymentFiltersRequest, GetPaymentMetricRequest, GetRefundFilterRequest,
- GetRefundMetricRequest, GetSdkEventFiltersRequest, GetSdkEventMetricRequest, ReportRequest,
+ GetDisputeMetricRequest, GetPaymentFiltersRequest, GetPaymentMetricRequest,
+ GetRefundFilterRequest, GetRefundMetricRequest, GetSdkEventFiltersRequest,
+ GetSdkEventMetricRequest, ReportRequest,
};
use error_stack::ResultExt;
use router_env::AnalyticsFlow;
@@ -92,6 +93,10 @@ pub mod routes {
web::resource("filters/disputes")
.route(web::post().to(get_dispute_filters)),
)
+ .service(
+ web::resource("metrics/disputes")
+ .route(web::post().to(get_dispute_metrics)),
+ )
}
route
}
@@ -612,4 +617,39 @@ pub mod routes {
))
.await
}
+ /// # Panics
+ ///
+ /// Panics if `json_payload` array does not contain one `GetDisputeMetricRequest` element.
+ pub async fn get_dispute_metrics(
+ state: web::Data<AppState>,
+ req: actix_web::HttpRequest,
+ json_payload: web::Json<[GetDisputeMetricRequest; 1]>,
+ ) -> impl Responder {
+ // safety: This shouldn't panic owing to the data type
+ #[allow(clippy::expect_used)]
+ let payload = json_payload
+ .into_inner()
+ .to_vec()
+ .pop()
+ .expect("Couldn't get GetDisputeMetricRequest");
+ let flow = AnalyticsFlow::GetDisputeMetrics;
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ payload,
+ |state, auth: AuthenticationData, req| async move {
+ analytics::disputes::get_metrics(
+ &state.pool,
+ &auth.merchant_account.merchant_id,
+ req,
+ )
+ .await
+ .map(ApplicationResponse::Json)
+ },
+ &auth::JWTAuth(Permission::Analytics),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+ }
}
diff --git a/crates/router/src/events.rs b/crates/router/src/events.rs
index 0091de588f1..0f309ce5de0 100644
--- a/crates/router/src/events.rs
+++ b/crates/router/src/events.rs
@@ -33,6 +33,7 @@ pub enum EventType {
ApiLogs,
ConnectorApiLogs,
OutgoingWebhookLogs,
+ Dispute,
}
#[derive(Debug, Default, Deserialize, Clone)]
diff --git a/crates/router/src/services/kafka.rs b/crates/router/src/services/kafka.rs
index ef9352e55b4..ab4a8948a6b 100644
--- a/crates/router/src/services/kafka.rs
+++ b/crates/router/src/services/kafka.rs
@@ -347,6 +347,7 @@ impl KafkaProducer {
EventType::Refund => &self.refund_analytics_topic,
EventType::ConnectorApiLogs => &self.connector_logs_topic,
EventType::OutgoingWebhookLogs => &self.outgoing_webhook_logs_topic,
+ EventType::Dispute => &self.dispute_analytics_topic,
}
}
}
diff --git a/crates/router/src/services/kafka/dispute.rs b/crates/router/src/services/kafka/dispute.rs
index 3ccdbe53cb1..2925bb5221d 100644
--- a/crates/router/src/services/kafka/dispute.rs
+++ b/crates/router/src/services/kafka/dispute.rs
@@ -7,7 +7,7 @@ use crate::types::storage::dispute::Dispute;
#[derive(serde::Serialize, Debug)]
pub struct KafkaDispute<'a> {
pub dispute_id: &'a String,
- pub amount: &'a String,
+ pub dispute_amount: i64,
pub currency: &'a String,
pub dispute_stage: &'a storage_enums::DisputeStage,
pub dispute_status: &'a storage_enums::DisputeStatus,
@@ -38,7 +38,7 @@ impl<'a> KafkaDispute<'a> {
pub fn from_storage(dispute: &'a Dispute) -> Self {
Self {
dispute_id: &dispute.dispute_id,
- amount: &dispute.amount,
+ dispute_amount: dispute.amount.parse::<i64>().unwrap_or_default(),
currency: &dispute.currency,
dispute_stage: &dispute.dispute_stage,
dispute_status: &dispute.dispute_status,
diff --git a/crates/router_env/src/lib.rs b/crates/router_env/src/lib.rs
index be6aa257d74..b68cdcc6fcc 100644
--- a/crates/router_env/src/lib.rs
+++ b/crates/router_env/src/lib.rs
@@ -55,6 +55,7 @@ pub enum AnalyticsFlow {
GetConnectorEvents,
GetOutgoingWebhookEvents,
GetDisputeFilters,
+ GetDisputeMetrics,
}
impl FlowMetric for AnalyticsFlow {}
|
2024-02-25T16:55:50Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [ ] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
adding metric api for dispute analytics
Http Method: ```POST```
URL Path ```/analytics/v1/metric/dispute```
### 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)?
-->
Hit the URL given below and should get sample response mentioned in the comment
## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
8b32dffe324a4cdbfde173cffe3fad2e839a52aa
|
|
juspay/hyperswitch
|
juspay__hyperswitch-3848
|
Bug: [FEATURE] : [Iatapay] mask pii information in connector request and response
### Feature Description
Mask pii information passed and received in the connector request and response
### Possible Implementation
Refactor all sensitive response and request fields secret
### 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/iatapay/transformers.rs b/crates/router/src/connector/iatapay/transformers.rs
index 55778af882b..b2507661395 100644
--- a/crates/router/src/connector/iatapay/transformers.rs
+++ b/crates/router/src/connector/iatapay/transformers.rs
@@ -261,7 +261,7 @@ pub struct IatapayPaymentsResponse {
pub status: IatapayPaymentStatus,
pub iata_payment_id: Option<String>,
pub iata_refund_id: Option<String>,
- pub merchant_id: Option<String>,
+ pub merchant_id: Option<Secret<String>>,
pub merchant_payment_id: Option<String>,
pub amount: f64,
pub currency: String,
@@ -428,7 +428,7 @@ pub struct RefundResponse {
iata_payment_id: Option<String>,
merchant_payment_id: Option<String>,
payment_amount: Option<f64>,
- merchant_id: Option<String>,
+ merchant_id: Option<Secret<String>>,
account_country: Option<String>,
}
|
2024-02-27T12:08:02Z
|
## 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 -->
Mask pii information passed and received in the connector request and response for Iatapay.
## Test Case
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
1. UPI Payment Create
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key:{{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": {
"vpa_id": "successtest@iata"
}
},
"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"
}
}'
```
2. Check if all the sensitive data in the `masked_response` is masked
```
curl --location '{{base_url}}/analytics/v1/connector_event_logs?type=Payment&payment_id={{payment_id}}' \
--header 'sec-ch-ua: "Not A(Brand";v="99", "Google Chrome";v="121", "Chromium";v="121"' \
--header 'sec-ch-ua-mobile: ?0' \
--header 'authorization: Bearer JWT_token' \
--header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36' \
--header 'Content-Type: application/json' \
--header 'Referer: https://integ.hyperswitch.io/' \
--header 'api-key: {{api-key}}' \
--header 'sec-ch-ua-platform: "macOS"'
```
Expected Response
```
\"masked_response\":\"{\\\"status\\\":\\\"CREATED\\\",\\\"iataPaymentId\\\":\\\"PH3WO013A5QTQ\\\",\\\"iataRefundId\\\":null,\\\"merchantId\\\":\\\"*** alloc::string::String ***\\\",\\\"merchantPaymentId\\\":\\\"pay_JBrbR1SRhIJ1BivCvB60_1\\\",\\\"amount\\\":50.0,\\\"currency\\\":\\\"INR\\\",\\\"checkoutMethods\\\":{\\\"redirect\\\":{\\\"redirectUrl\\\":\\\"https://sandbox.iata-pay.iata.org/api/v1/payments/PH3WO013A5QTQ/checkout/redirect\\\"}},\\\"failureCode\\\":null,\\\"failureDetails\\\":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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
0626ca968576709a3559243f5a64e742201dbf91
|
|
juspay/hyperswitch
|
juspay__hyperswitch-3846
|
Bug: [BUG] [AUTHORIZEDOTNET] Wrong Status Mapping
### Bug Description
The status mapping for connector Authorizdotnet does not mark the payment charged until it is settled.
### Expected Behavior
The status mapping for connector Authorizdotnet should mark the payment charged when it is approved even though it is not settled.
### Actual Behavior
The status mapping for connector Authorizdotnet does not mark the payment charged until it is settled.
### 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/authorizedotnet.rs b/crates/router/src/connector/authorizedotnet.rs
index ba232c01bbf..0aba48fa5e5 100644
--- a/crates/router/src/connector/authorizedotnet.rs
+++ b/crates/router/src/connector/authorizedotnet.rs
@@ -9,7 +9,10 @@ use transformers as authorizedotnet;
use crate::{
configs::settings,
- connector::utils as connector_utils,
+ connector::{
+ utils as connector_utils,
+ utils::{PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData},
+ },
consts,
core::{
errors::{self, CustomResult},
@@ -216,11 +219,14 @@ 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,
- })
+ types::RouterData::try_from((
+ types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ },
+ true,
+ ))
}
fn get_error_response(
@@ -405,11 +411,14 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
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::try_from((
+ types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ },
+ data.request.is_auto_capture()?,
+ ))
}
fn get_error_response(
@@ -783,11 +792,14 @@ impl
.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::try_from((
+ types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ },
+ data.request.is_auto_capture()?,
+ ))
}
fn get_error_response(
diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs
index eb5f13881fb..e2718d1ac91 100644
--- a/crates/router/src/connector/authorizedotnet/transformers.rs
+++ b/crates/router/src/connector/authorizedotnet/transformers.rs
@@ -10,7 +10,7 @@ use crate::{
connector::utils::{self, CardData, PaymentsSyncRequestData, RefundsRequestData, WalletData},
core::errors,
services,
- types::{self, api, storage::enums},
+ types::{self, api, storage::enums, transformers::ForeignFrom},
utils::OptionExt,
};
@@ -258,8 +258,8 @@ struct TransactionVoidOrCaptureRequest {
#[serde(rename_all = "camelCase")]
pub struct AuthorizedotnetPaymentsRequest {
merchant_authentication: AuthorizedotnetAuthType,
+ ref_id: Option<String>,
transaction_request: TransactionRequest,
- ref_id: String,
}
#[derive(Debug, Serialize)]
@@ -326,12 +326,16 @@ impl TryFrom<&AuthorizedotnetRouterData<&types::PaymentsAuthorizeRouterData>>
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,
- ref_id: item.router_data.connector_request_reference_id.clone(),
},
})
}
@@ -413,10 +417,16 @@ pub enum AuthorizedotnetRefundStatus {
HeldForReview,
}
-impl From<AuthorizedotnetPaymentStatus> for enums::AttemptStatus {
- fn from(item: AuthorizedotnetPaymentStatus) -> Self {
+impl ForeignFrom<(AuthorizedotnetPaymentStatus, bool)> for enums::AttemptStatus {
+ fn foreign_from((item, auto_capture): (AuthorizedotnetPaymentStatus, bool)) -> Self {
match item {
- AuthorizedotnetPaymentStatus::Approved => Self::Pending,
+ AuthorizedotnetPaymentStatus::Approved => {
+ if auto_capture {
+ Self::Charged
+ } else {
+ Self::Authorized
+ }
+ }
AuthorizedotnetPaymentStatus::Declined | AuthorizedotnetPaymentStatus::Error => {
Self::Failure
}
@@ -536,35 +546,44 @@ pub enum AuthorizedotnetVoidStatus {
impl From<AuthorizedotnetVoidStatus> for enums::AttemptStatus {
fn from(item: AuthorizedotnetVoidStatus) -> Self {
match item {
- AuthorizedotnetVoidStatus::Approved => Self::VoidInitiated,
- AuthorizedotnetVoidStatus::Declined | AuthorizedotnetVoidStatus::Error => Self::Failure,
- AuthorizedotnetVoidStatus::HeldForReview => Self::Pending,
+ AuthorizedotnetVoidStatus::Approved => Self::Voided,
+ AuthorizedotnetVoidStatus::Declined | AuthorizedotnetVoidStatus::Error => {
+ Self::VoidFailed
+ }
+ AuthorizedotnetVoidStatus::HeldForReview => Self::VoidInitiated,
}
}
}
impl<F, T>
- TryFrom<
+ TryFrom<(
types::ResponseRouterData<
F,
AuthorizedotnetPaymentsResponse,
T,
types::PaymentsResponseData,
>,
- > for types::RouterData<F, T, types::PaymentsResponseData>
+ bool,
+ )> for types::RouterData<F, T, types::PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<
- F,
- AuthorizedotnetPaymentsResponse,
- T,
- types::PaymentsResponseData,
- >,
+ (item, is_auto_capture): (
+ types::ResponseRouterData<
+ F,
+ AuthorizedotnetPaymentsResponse,
+ T,
+ types::PaymentsResponseData,
+ >,
+ bool,
+ ),
) -> Result<Self, Self::Error> {
match &item.response.transaction_response {
Some(TransactionResponse::AuthorizedotnetTransactionResponse(transaction_response)) => {
- let status = enums::AttemptStatus::from(transaction_response.response_code.clone());
+ let status = enums::AttemptStatus::foreign_from((
+ transaction_response.response_code.clone(),
+ is_auto_capture,
+ ));
let error = transaction_response.errors.as_ref().and_then(|errors| {
errors.iter().next().map(|error| types::ErrorResponse {
code: error.error_code.clone(),
|
2024-02-27T10:08:46Z
|
## 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 status mapping for connector `Authorizdotnet` is fixed.
- The `ref_id` field being passed in connector contains `connector_request_reference_id`. The max number of characters allowed in ref_id is 20 and hence a check has been added to only pass ref_id if connector_request_reference_id contains `less than or equal to` 20 characters.
### 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/3846
https://github.com/juspay/hyperswitch/issues/3847
## 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)?
-->
Following flows should be tested for connector Authorizdotnet:
1. Authorization(Auto Capture):
```
{
"payment_id": "abcd1",
"amount": 800,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"customer_id": "StripeCustomer",
"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"
}
}
}
```
NOTE: Try passing the above curl without payment_id also.
Response:
```
{
"payment_id": "abcd1",
"merchant_id": "merchant_1708944265",
"status": "succeeded",
"amount": 800,
"net_amount": 800,
"amount_capturable": 0,
"amount_received": 800,
"connector": "authorizedotnet",
"client_secret": "abcd1_secret_eiryjwdDZgV6IFO8TeEu",
"created": "2024-02-27T13:19:55.615Z",
"currency": "USD",
"customer_id": "StripeCustomer",
"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": "4242",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "424242",
"card_extended_bin": "42424242",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe"
}
},
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": "guest@example.com",
"name": "John 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": "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": 1709039995,
"expires": 1709043595,
"secret": "epk_d639baf128604e01adc764d9d48437c6"
},
"manual_retry_allowed": false,
"connector_transaction_id": "80015300949",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "80015300949",
"payment_link": null,
"profile_id": "pro_9LdgkmKiHJ2dR3oUn5Ow",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_HDQdFPQctm5R737tT7qf",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"expires_on": "2024-02-27T13:34:55.615Z",
"fingerprint": null
}
```
2. Authorization(Manual Capture):
```
{
"payment_id": "1ss",
"amount": 800,
"currency": "USD",
"confirm": true,
"capture_method": "manual",
"customer_id": "StripeCustomer",
"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"
}
}
}
```
NOTE: Try passing the above curl without payment_id also.
Response:
```
{
"payment_id": "1ss",
"merchant_id": "merchant_1708944265",
"status": "requires_capture",
"amount": 1200,
"net_amount": 1200,
"amount_capturable": 1200,
"amount_received": null,
"connector": "authorizedotnet",
"client_secret": "1ss_secret_4DnENIEpIUKKKnoKKElP",
"created": "2024-02-27T13:20:40.683Z",
"currency": "USD",
"customer_id": "StripeCustomer",
"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": "4242",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "424242",
"card_extended_bin": "42424242",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe"
}
},
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": "guest@example.com",
"name": "John 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": "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": 1709040040,
"expires": 1709043640,
"secret": "epk_a94c6c4d1e594998a168081802130610"
},
"manual_retry_allowed": false,
"connector_transaction_id": "80015300969",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "80015300969",
"payment_link": null,
"profile_id": "pro_9LdgkmKiHJ2dR3oUn5Ow",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_HDQdFPQctm5R737tT7qf",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"expires_on": "2024-02-27T13:35:40.683Z",
"fingerprint": null
}
```
3. Capture:
```
curl --location 'http://localhost:8080/payments/1ss/capture' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: API_KEY_HERE' \
--data '{}'
```
Response:
```
{
"payment_id": "1ss",
"merchant_id": "merchant_1708944265",
"status": "succeeded",
"amount": 1200,
"net_amount": 1200,
"amount_capturable": 0,
"amount_received": 1200,
"connector": "authorizedotnet",
"client_secret": "1ss_secret_4DnENIEpIUKKKnoKKElP",
"created": "2024-02-27T13:20:40.683Z",
"currency": "USD",
"customer_id": "StripeCustomer",
"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": "4242",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "424242",
"card_extended_bin": "42424242",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe"
}
},
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": "guest@example.com",
"name": "John 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": "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": "80015300969",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "80015300969",
"payment_link": null,
"profile_id": "pro_9LdgkmKiHJ2dR3oUn5Ow",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_HDQdFPQctm5R737tT7qf",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"expires_on": "2024-02-27T13:35:40.683Z",
"fingerprint": null
}
```
4. Void:
```
curl --location 'http://localhost:8080/payments/1s2/cancel' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: API_KEY_HERE' \
--data '{}'
```
Response:
```
{
"payment_id": "1s2",
"merchant_id": "merchant_1708944265",
"status": "cancelled",
"amount": 120,
"net_amount": 120,
"amount_capturable": 0,
"amount_received": null,
"connector": "authorizedotnet",
"client_secret": "1s2_secret_f0Q0ROMla0buxvBmaqR9",
"created": "2024-02-27T13:22:23.892Z",
"currency": "USD",
"customer_id": "StripeCustomer",
"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": "4242",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "424242",
"card_extended_bin": "42424242",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe"
}
},
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": "guest@example.com",
"name": "John 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": "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": "80015301006",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "80015301006",
"payment_link": null,
"profile_id": "pro_9LdgkmKiHJ2dR3oUn5Ow",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_HDQdFPQctm5R737tT7qf",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"expires_on": "2024-02-27T13:37:23.892Z",
"fingerprint": 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
0626ca968576709a3559243f5a64e742201dbf91
|
|
juspay/hyperswitch
|
juspay__hyperswitch-3847
|
Bug: [BUG] [AUTHORIZEDOTNET] REF_ID should only allow strings which have less than 20 charcaters
### Bug Description
The ref_id field being passed in connector contains connector_request_reference_id. The max number of characters allowed in ref_id is 20 while the current implementation allows it to be more than 20 characters which results in the payment getting failed at the connector end.
### Expected Behavior
REF_ID should not be passed if `connector_request_reference_id` is greater than 20 characters.
### Actual Behavior
REF_ID is passed even if `connector_request_reference_id` is greater than 20 characters.
### 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/authorizedotnet.rs b/crates/router/src/connector/authorizedotnet.rs
index ba232c01bbf..0aba48fa5e5 100644
--- a/crates/router/src/connector/authorizedotnet.rs
+++ b/crates/router/src/connector/authorizedotnet.rs
@@ -9,7 +9,10 @@ use transformers as authorizedotnet;
use crate::{
configs::settings,
- connector::utils as connector_utils,
+ connector::{
+ utils as connector_utils,
+ utils::{PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData},
+ },
consts,
core::{
errors::{self, CustomResult},
@@ -216,11 +219,14 @@ 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,
- })
+ types::RouterData::try_from((
+ types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ },
+ true,
+ ))
}
fn get_error_response(
@@ -405,11 +411,14 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
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::try_from((
+ types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ },
+ data.request.is_auto_capture()?,
+ ))
}
fn get_error_response(
@@ -783,11 +792,14 @@ impl
.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::try_from((
+ types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ },
+ data.request.is_auto_capture()?,
+ ))
}
fn get_error_response(
diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs
index eb5f13881fb..e2718d1ac91 100644
--- a/crates/router/src/connector/authorizedotnet/transformers.rs
+++ b/crates/router/src/connector/authorizedotnet/transformers.rs
@@ -10,7 +10,7 @@ use crate::{
connector::utils::{self, CardData, PaymentsSyncRequestData, RefundsRequestData, WalletData},
core::errors,
services,
- types::{self, api, storage::enums},
+ types::{self, api, storage::enums, transformers::ForeignFrom},
utils::OptionExt,
};
@@ -258,8 +258,8 @@ struct TransactionVoidOrCaptureRequest {
#[serde(rename_all = "camelCase")]
pub struct AuthorizedotnetPaymentsRequest {
merchant_authentication: AuthorizedotnetAuthType,
+ ref_id: Option<String>,
transaction_request: TransactionRequest,
- ref_id: String,
}
#[derive(Debug, Serialize)]
@@ -326,12 +326,16 @@ impl TryFrom<&AuthorizedotnetRouterData<&types::PaymentsAuthorizeRouterData>>
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,
- ref_id: item.router_data.connector_request_reference_id.clone(),
},
})
}
@@ -413,10 +417,16 @@ pub enum AuthorizedotnetRefundStatus {
HeldForReview,
}
-impl From<AuthorizedotnetPaymentStatus> for enums::AttemptStatus {
- fn from(item: AuthorizedotnetPaymentStatus) -> Self {
+impl ForeignFrom<(AuthorizedotnetPaymentStatus, bool)> for enums::AttemptStatus {
+ fn foreign_from((item, auto_capture): (AuthorizedotnetPaymentStatus, bool)) -> Self {
match item {
- AuthorizedotnetPaymentStatus::Approved => Self::Pending,
+ AuthorizedotnetPaymentStatus::Approved => {
+ if auto_capture {
+ Self::Charged
+ } else {
+ Self::Authorized
+ }
+ }
AuthorizedotnetPaymentStatus::Declined | AuthorizedotnetPaymentStatus::Error => {
Self::Failure
}
@@ -536,35 +546,44 @@ pub enum AuthorizedotnetVoidStatus {
impl From<AuthorizedotnetVoidStatus> for enums::AttemptStatus {
fn from(item: AuthorizedotnetVoidStatus) -> Self {
match item {
- AuthorizedotnetVoidStatus::Approved => Self::VoidInitiated,
- AuthorizedotnetVoidStatus::Declined | AuthorizedotnetVoidStatus::Error => Self::Failure,
- AuthorizedotnetVoidStatus::HeldForReview => Self::Pending,
+ AuthorizedotnetVoidStatus::Approved => Self::Voided,
+ AuthorizedotnetVoidStatus::Declined | AuthorizedotnetVoidStatus::Error => {
+ Self::VoidFailed
+ }
+ AuthorizedotnetVoidStatus::HeldForReview => Self::VoidInitiated,
}
}
}
impl<F, T>
- TryFrom<
+ TryFrom<(
types::ResponseRouterData<
F,
AuthorizedotnetPaymentsResponse,
T,
types::PaymentsResponseData,
>,
- > for types::RouterData<F, T, types::PaymentsResponseData>
+ bool,
+ )> for types::RouterData<F, T, types::PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<
- F,
- AuthorizedotnetPaymentsResponse,
- T,
- types::PaymentsResponseData,
- >,
+ (item, is_auto_capture): (
+ types::ResponseRouterData<
+ F,
+ AuthorizedotnetPaymentsResponse,
+ T,
+ types::PaymentsResponseData,
+ >,
+ bool,
+ ),
) -> Result<Self, Self::Error> {
match &item.response.transaction_response {
Some(TransactionResponse::AuthorizedotnetTransactionResponse(transaction_response)) => {
- let status = enums::AttemptStatus::from(transaction_response.response_code.clone());
+ let status = enums::AttemptStatus::foreign_from((
+ transaction_response.response_code.clone(),
+ is_auto_capture,
+ ));
let error = transaction_response.errors.as_ref().and_then(|errors| {
errors.iter().next().map(|error| types::ErrorResponse {
code: error.error_code.clone(),
|
2024-02-27T10:08:46Z
|
## 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 status mapping for connector `Authorizdotnet` is fixed.
- The `ref_id` field being passed in connector contains `connector_request_reference_id`. The max number of characters allowed in ref_id is 20 and hence a check has been added to only pass ref_id if connector_request_reference_id contains `less than or equal to` 20 characters.
### 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/3846
https://github.com/juspay/hyperswitch/issues/3847
## 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)?
-->
Following flows should be tested for connector Authorizdotnet:
1. Authorization(Auto Capture):
```
{
"payment_id": "abcd1",
"amount": 800,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"customer_id": "StripeCustomer",
"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"
}
}
}
```
NOTE: Try passing the above curl without payment_id also.
Response:
```
{
"payment_id": "abcd1",
"merchant_id": "merchant_1708944265",
"status": "succeeded",
"amount": 800,
"net_amount": 800,
"amount_capturable": 0,
"amount_received": 800,
"connector": "authorizedotnet",
"client_secret": "abcd1_secret_eiryjwdDZgV6IFO8TeEu",
"created": "2024-02-27T13:19:55.615Z",
"currency": "USD",
"customer_id": "StripeCustomer",
"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": "4242",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "424242",
"card_extended_bin": "42424242",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe"
}
},
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": "guest@example.com",
"name": "John 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": "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": 1709039995,
"expires": 1709043595,
"secret": "epk_d639baf128604e01adc764d9d48437c6"
},
"manual_retry_allowed": false,
"connector_transaction_id": "80015300949",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "80015300949",
"payment_link": null,
"profile_id": "pro_9LdgkmKiHJ2dR3oUn5Ow",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_HDQdFPQctm5R737tT7qf",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"expires_on": "2024-02-27T13:34:55.615Z",
"fingerprint": null
}
```
2. Authorization(Manual Capture):
```
{
"payment_id": "1ss",
"amount": 800,
"currency": "USD",
"confirm": true,
"capture_method": "manual",
"customer_id": "StripeCustomer",
"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"
}
}
}
```
NOTE: Try passing the above curl without payment_id also.
Response:
```
{
"payment_id": "1ss",
"merchant_id": "merchant_1708944265",
"status": "requires_capture",
"amount": 1200,
"net_amount": 1200,
"amount_capturable": 1200,
"amount_received": null,
"connector": "authorizedotnet",
"client_secret": "1ss_secret_4DnENIEpIUKKKnoKKElP",
"created": "2024-02-27T13:20:40.683Z",
"currency": "USD",
"customer_id": "StripeCustomer",
"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": "4242",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "424242",
"card_extended_bin": "42424242",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe"
}
},
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": "guest@example.com",
"name": "John 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": "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": 1709040040,
"expires": 1709043640,
"secret": "epk_a94c6c4d1e594998a168081802130610"
},
"manual_retry_allowed": false,
"connector_transaction_id": "80015300969",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "80015300969",
"payment_link": null,
"profile_id": "pro_9LdgkmKiHJ2dR3oUn5Ow",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_HDQdFPQctm5R737tT7qf",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"expires_on": "2024-02-27T13:35:40.683Z",
"fingerprint": null
}
```
3. Capture:
```
curl --location 'http://localhost:8080/payments/1ss/capture' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: API_KEY_HERE' \
--data '{}'
```
Response:
```
{
"payment_id": "1ss",
"merchant_id": "merchant_1708944265",
"status": "succeeded",
"amount": 1200,
"net_amount": 1200,
"amount_capturable": 0,
"amount_received": 1200,
"connector": "authorizedotnet",
"client_secret": "1ss_secret_4DnENIEpIUKKKnoKKElP",
"created": "2024-02-27T13:20:40.683Z",
"currency": "USD",
"customer_id": "StripeCustomer",
"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": "4242",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "424242",
"card_extended_bin": "42424242",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe"
}
},
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": "guest@example.com",
"name": "John 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": "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": "80015300969",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "80015300969",
"payment_link": null,
"profile_id": "pro_9LdgkmKiHJ2dR3oUn5Ow",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_HDQdFPQctm5R737tT7qf",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"expires_on": "2024-02-27T13:35:40.683Z",
"fingerprint": null
}
```
4. Void:
```
curl --location 'http://localhost:8080/payments/1s2/cancel' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: API_KEY_HERE' \
--data '{}'
```
Response:
```
{
"payment_id": "1s2",
"merchant_id": "merchant_1708944265",
"status": "cancelled",
"amount": 120,
"net_amount": 120,
"amount_capturable": 0,
"amount_received": null,
"connector": "authorizedotnet",
"client_secret": "1s2_secret_f0Q0ROMla0buxvBmaqR9",
"created": "2024-02-27T13:22:23.892Z",
"currency": "USD",
"customer_id": "StripeCustomer",
"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": "4242",
"card_type": null,
"card_network": null,
"card_issuer": null,
"card_issuing_country": null,
"card_isin": "424242",
"card_extended_bin": "42424242",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe"
}
},
"payment_token": null,
"shipping": null,
"billing": null,
"order_details": null,
"email": "guest@example.com",
"name": "John 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": "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": "80015301006",
"frm_message": null,
"metadata": null,
"connector_metadata": null,
"feature_metadata": null,
"reference_id": "80015301006",
"payment_link": null,
"profile_id": "pro_9LdgkmKiHJ2dR3oUn5Ow",
"surcharge_details": null,
"attempt_count": 1,
"merchant_decision": null,
"merchant_connector_id": "mca_HDQdFPQctm5R737tT7qf",
"incremental_authorization_allowed": null,
"authorization_count": null,
"incremental_authorizations": null,
"expires_on": "2024-02-27T13:37:23.892Z",
"fingerprint": 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
0626ca968576709a3559243f5a64e742201dbf91
|
|
juspay/hyperswitch
|
juspay__hyperswitch-3843
|
Bug: [FEATURE] : [Gocardless] mask pii information in connector request and response
### Feature Description
Mask pii information passed and received in the connector request and response
### Possible Implementation
Refactor all sensitive response and request fields secret
### 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/gocardless/transformers.rs b/crates/router/src/connector/gocardless/transformers.rs
index d3703bc6bf8..21fc44fe84f 100644
--- a/crates/router/src/connector/gocardless/transformers.rs
+++ b/crates/router/src/connector/gocardless/transformers.rs
@@ -547,7 +547,7 @@ pub struct GocardlessMandateResponse {
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct MandateResponse {
- id: String,
+ id: Secret<String>,
}
impl<F>
@@ -570,7 +570,7 @@ impl<F>
>,
) -> Result<Self, Self::Error> {
let mandate_reference = Some(MandateReference {
- connector_mandate_id: Some(item.response.mandates.id.clone()),
+ connector_mandate_id: Some(item.response.mandates.id.clone().expose()),
payment_method_id: None,
});
Ok(Self {
|
2024-02-27T10:00:29Z
|
## 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 -->
Mask pii information passed and received in the connector request and response for Gocardless.
## Test Case
1. Create a payment intent with Gocardless
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: {{}}' \
--data-raw '{
"amount": 0,
"order_details": null,
"currency": "USD",
"confirm": false,
"capture_method": "automatic",
"authentication_type": "three_ds",
"customer_id": "arjun",
"email": "hyperswitch_sdk_demo_id@gmail.com",
"description": "Hello this is description",
"shipping": {
"address": {
"state": "zsaasdas",
"city": "Banglore",
"country": "US",
"line1": "sdsdfsdf",
"line2": "hsgdbhd",
"line3": "alsksoe",
"zip": "571201",
"first_name": "joseph",
"last_name": "doe"
},
"phone": {
"number": "123456789",
"country_code": "+1"
}
},
"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": {},
"setup_future_usage": "off_session",
"mandate_data": {
"mandate_type": {
"multi_use": {
"amount": 1000,
"currency": "USD"
}
}
}
}'
```
2.Confirm the mandate payment
```
curl --location 'http://localhost:8080/payments/pay_FXMSggPlgoGMg9r6AlpY/confirm' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_BRdlOJtJTl8WPK503hzNIbM8mTJC7Ayp1D4tiMyP9JzUXTEvR1N65YLI4uy7C2w2' \
--data-raw '{
"return_url": "http://localhost:9060/completion",
"payment_method": "bank_debit",
"setup_future_usage": "off_session",
"payment_method_type": "ach",
"payment_type": "setup_mandate",
"payment_method_data": {
"bank_debit": {
"ach_bank_debit": {
"billing_details": {
"name": "Shivam S",
"email": "test@test.com",
"address": {
"line1": "123",
"line2": "123",
"city": "vjnsf",
"state": "Alaska",
"zip": "10001",
"country": "US"
}
},
"account_number": "27155003358",
"bank_account_holder_name": "tests tests",
"routing_number": "026073150",
"bank_type": "checking"
}
}
},
"mandate_data": {
"customer_acceptance": {
"acceptance_type": "online",
"accepted_at": "2023-12-07T12:16:08.622Z",
"online": {
"user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36"
}
}
},
"browser_info": {
"user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36",
"accept_header": "text\\/html,application\\/xhtml+xml,application\\/xml;q=0.9,image\\/webp,image\\/apng,*\\/*;q=0.8",
"language": "en-GB",
"color_depth": 24,
"screen_height": 1440,
"screen_width": 2560,
"time_zone": -330,
"java_enabled": true,
"java_script_enabled": true,
"ip_address": "0.0.0.0"
}
}'
```
3. Check if all the sensitive data in the `masked_response` is masked
```
curl --location '{{base_url}}/analytics/v1/connector_event_logs?type=Payment&payment_id={{payment_id}}' \
--header 'sec-ch-ua: "Not A(Brand";v="99", "Google Chrome";v="121", "Chromium";v="121"' \
--header 'sec-ch-ua-mobile: ?0' \
--header 'authorization: Bearer JWT_token' \
--header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36' \
--header 'Content-Type: application/json' \
--header 'Referer: https://integ.hyperswitch.io/' \
--header 'api-key: {{api-key}}' \
--header 'sec-ch-ua-platform: "macOS"'
```
Response should contain:
```
"masked_response\":\"{\\\"mandates\\\":{\\\"id\\\":\\\"*** alloc::string::String ***\\\"}}
```
## 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
|
cd1a17bcd260629aad7548ff274f5512c37bfab7
|
|
juspay/hyperswitch
|
juspay__hyperswitch-3833
|
Bug: [Bug] metadata validation for update payment connector
Metadata validation in update payment connector happens even if we don't pass metadata in the request. Instead, if metadata is not present we should consider MCA metadata in update_payment_connector function .
|
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index 2b87d64c6ac..14c88448125 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -1185,6 +1185,7 @@ pub async fn update_payment_connector(
field_name: "connector_account_details".to_string(),
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)
.into_report()
@@ -1192,27 +1193,27 @@ 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, &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(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(),
+ }),
+ })?;
let (connector_status, disabled) =
validate_status_and_disabled(req.status, req.disabled, auth, mca.status)?;
|
2024-02-27T05:55: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 -->
Metadata validation in update payment connector happens even if we don't pass metadata in the request. This pr fixes metadata validation in update payment connector function. If metadata is not present we consider mca metadata.
### 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).
-->
Metadata validation in update payment connector happens even if we don't pass metadata in the request. This pr fixes metadata validation in update payment connector function. If metadata is not present we consider mca metadata.
## 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)?
-->
**Test case 1 :**
step 1 : Create merchant connector account for Fiserv.
```
curl --location --request POST 'https://sandbox.hyperswitch.io/account/<merchant_Id>/connectors' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data-raw '{
"connector_type": "fiz_operations",
"connector_name": "fiserv",
"connector_account_details": {
"auth_type": "SignatureKey",
"api_key": "API_KEY",
"key1": "KEY1",
"api_secret": "API_SECRET"
},
"test_mode": true,
"disabled": false,
"payment_methods_enabled": [
{
"payment_method": "card",
"payment_method_types": [
{
"payment_method_type": "credit",
"card_networks": [
"Visa",
"Mastercard"
],
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "debit",
"card_networks": [
"Visa",
"Mastercard"
],
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
},
{
"payment_method": "pay_later",
"payment_method_types": [
{
"payment_method_type": "klarna",
"payment_experience": "redirect_to_url",
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "affirm",
"payment_experience": "redirect_to_url",
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "afterpay_clearpay",
"payment_experience": "redirect_to_url",
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
},
{
"payment_method": "bank_redirect",
"payment_method_types": [
{
"payment_method_type": "eps",
"recurring_enabled": true,
"installment_payment_enabled": true
},
{
"payment_method_type": "sofort",
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
}
],
"metadata": {
"terminal_id":"TERMINAL_ID"
}
}'
```
step 2 : Update merchant connector account without updating metadata, It should not throw 422.
here below curl is updating connector webhook details.
```
curl --location --request POST 'https://sandbox.hyperswitch.io/account/<merchant_id>/connectors/<mca_id>' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data-raw '{
"connector_type": "fiz_operations",
"connector_webhook_details": {
"merchant_secret": "MERCHANT_SECRET",
"additional_secret": null
}
}'
```
**Test case 2 :**
step 1 : Pass metadata in create payment connector for fiserv. curl is same as test case 1 -> step1
step 2 : Pass valid metadata in update payment connector, This should update metadata.
where valid metadata for fiserv is `{"terminal_id": "TERMINAL_ID"}`
```
curl --location --request POST 'https://sandbox.hyperswitch.io/account/<merchant_id>/connectors/<mca_id>' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data-raw '{
"connector_type": "fiz_operations",
"metadata": {"terminal_id": "DIFFERENT_TERMINAL_ID"}
}'
```
**Test case 3 :**
step 1 : Pass metadata in create payment connector for fiserv. curl is same as test case 1 -> step1
step 2 : Pass Invalid metadata or empty metadata in update payment connector, This should throw error.
```
curl --location --request POST 'https://sandbox.hyperswitch.io/account/<merchant_id>/connectors/<mca_id>' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data-raw '{
"connector_type": "fiz_operations",
"metadata": {}
}'
```
This can be done for any other connector which have metadata validation while creating merchant connector account(Braintree, Coinbase ).
## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
2b0fbc70749338d5c501bbb782d6fc4747890d61
|
|
juspay/hyperswitch
|
juspay__hyperswitch-3841
|
Bug: [FEATURE] : [Globalpay] mask pii information in connector request and response
### Feature Description
Mask pii information passed and received in the connector request and response
### Possible Implementation
Refactor all sensitive response and request fields secret
### 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/globalpay/requests.rs b/crates/router/src/connector/globalpay/requests.rs
index ee62e8c2c2c..1e5413bc838 100644
--- a/crates/router/src/connector/globalpay/requests.rs
+++ b/crates/router/src/connector/globalpay/requests.rs
@@ -41,7 +41,7 @@ pub struct GlobalpayPaymentsRequest {
/// Indicates whether the Merchant or the Payer initiated the creation of a transaction.
pub initiator: Option<Initiator>,
/// Indicates the source IP Address of the system used to create the transaction.
- pub ip_address: Option<String>,
+ pub ip_address: Option<Secret<String, common_utils::pii::IpAddress>>,
/// Indicates the language the transaction was executed in. In the format ISO-639-1 (alpha-2)
/// or ISO-639-1 (alpha-2)_ISO-3166(alpha-2)
pub language: Option<Language>,
@@ -80,8 +80,8 @@ pub struct GlobalpayPaymentsRequest {
#[derive(Debug, Serialize)]
pub struct GlobalpayRefreshTokenRequest {
pub app_id: Secret<String>,
- pub nonce: String,
- pub secret: String,
+ pub nonce: Secret<String>,
+ pub secret: Secret<String>,
pub grant_type: String,
}
@@ -106,10 +106,10 @@ pub struct Device {
/// Describes the receipts a device prints when processing a transaction.
pub print_receipt_mode: Option<PrintReceiptMode>,
/// The sequence number from the device used to align with processing platform.
- pub sequence_number: Option<String>,
+ pub sequence_number: Option<Secret<String>>,
/// A unique identifier for the physical device. This value persists with the device even if
/// it is repurposed.
- pub serial_number: Option<String>,
+ pub serial_number: Option<Secret<String>>,
/// The time from the device in ISO8601 format
pub time: Option<String>,
}
@@ -209,15 +209,15 @@ pub struct PaymentMethod {
/// Indicates whether to execute the fingerprint signature functionality.
pub fingerprint_mode: Option<FingerprintMode>,
/// Specify the first name of the owner of the payment method.
- pub first_name: Option<String>,
+ pub first_name: Option<Secret<String>>,
/// Unique Global Payments generated id used to reference a stored payment method on the
/// Global Payments system. Often referred to as the payment method token. This value can be
/// used instead of payment method details such as a card number and expiry date.
- pub id: Option<String>,
+ pub id: Option<Secret<String>>,
/// Specify the surname of the owner of the payment method.
- pub last_name: Option<String>,
+ pub last_name: Option<Secret<String>>,
/// The full name of the owner of the payment method.
- pub name: Option<String>,
+ pub name: Option<Secret<String>>,
/// Contains the value a merchant wishes to appear on the payer's payment method statement
/// for this transaction
pub narrative: Option<String>,
@@ -274,11 +274,11 @@ pub struct ThreeDs {
pub struct BankTransfer {
/// The number or reference for the payer's bank account.
- pub account_number: Option<String>,
+ pub account_number: Option<Secret<String>>,
pub bank: Option<Bank>,
/// The number or reference for the check
- pub check_reference: Option<String>,
+ pub check_reference: Option<Secret<String>>,
/// The type of bank account associated with the payer's bank account.
pub number_type: Option<NumberType>,
/// Indicates how the transaction was authorized by the merchant.
@@ -289,7 +289,7 @@ pub struct BankTransfer {
pub struct Bank {
pub address: Option<Address>,
/// The local identifier code for the bank.
- pub code: Option<String>,
+ pub code: Option<Secret<String>>,
/// The name of the bank.
pub name: Option<String>,
}
@@ -297,17 +297,17 @@ pub struct Bank {
#[derive(Debug, Serialize, Deserialize)]
pub struct Address {
/// Merchant defined field common to all transactions that are part of the same order.
- pub city: Option<String>,
+ pub city: Option<Secret<String>>,
/// The country in ISO-3166-1(alpha-2 code) format.
pub country: Option<String>,
/// First line of the address.
- pub line_1: Option<String>,
+ pub line_1: Option<Secret<String>>,
/// Second line of the address.
- pub line_2: Option<String>,
+ pub line_2: Option<Secret<String>>,
/// Third line of the address.
- pub line_3: Option<String>,
+ pub line_3: Option<Secret<String>>,
/// The city or town of the address.
- pub postal_code: Option<String>,
+ pub postal_code: Option<Secret<String>>,
/// The state or region of the address. ISO 3166-2 minus the country code itself. For
/// example, US Illinois = IL, or in the case of GB counties Wiltshire = WI or Aberdeenshire
/// = ABD
@@ -319,7 +319,7 @@ pub struct Card {
/// The card providers description of their card product.
pub account_type: Option<String>,
/// Code generated when the card is successfully authorized.
- pub authcode: Option<String>,
+ pub authcode: Option<Secret<String>>,
/// First line of the address associated with the card.
pub avs_address: Option<String>,
/// Postal code of the address associated with the card.
@@ -340,11 +340,11 @@ pub struct Card {
/// The the card account number used to authorize the transaction. Also known as PAN.
pub number: cards::CardNumber,
/// Contains the pin block info, relating to the pin code the Payer entered.
- pub pin_block: Option<String>,
+ pub pin_block: Option<Secret<String>>,
/// The full card tag data for an EMV/chip card transaction.
- pub tag: Option<String>,
+ pub tag: Option<Secret<String>>,
/// Data from magnetic stripe of a card
- pub track: Option<String>,
+ pub track: Option<Secret<String>>,
}
#[derive(Debug, Serialize, Deserialize)]
@@ -358,7 +358,7 @@ pub struct DigitalWallet {
#[derive(Debug, Serialize, Deserialize)]
pub struct Encryption {
/// The encryption info used when sending encrypted card data to Global Payments.
- pub info: Option<String>,
+ pub info: Option<Secret<String>>,
/// The encryption method used when sending encrypted card data to Global Payments.
pub method: Option<Method>,
/// The version of encryption being used.
diff --git a/crates/router/src/connector/globalpay/response.rs b/crates/router/src/connector/globalpay/response.rs
index 201297c399e..7d5efadaff8 100644
--- a/crates/router/src/connector/globalpay/response.rs
+++ b/crates/router/src/connector/globalpay/response.rs
@@ -6,9 +6,9 @@ use super::requests;
#[derive(Debug, Serialize, Deserialize)]
pub struct GlobalpayPaymentsResponse {
/// A unique identifier for the merchant account set by Global Payments.
- pub account_id: Option<String>,
+ pub account_id: Option<Secret<String>>,
/// A meaningful label for the merchant account set by Global Payments.
- pub account_name: Option<String>,
+ pub account_name: Option<Secret<String>>,
/// Information about the Action executed.
pub action: Option<Action>,
/// The amount to transfer between Payer and Merchant for a SALE or a REFUND. It is always
@@ -37,7 +37,7 @@ pub struct GlobalpayPaymentsResponse {
/// A unique identifier for the merchant set by Global Payments.
pub merchant_id: Option<String>,
/// A meaningful label for the merchant set by Global Payments.
- pub merchant_name: Option<String>,
+ pub merchant_name: Option<Secret<String>>,
pub payment_method: Option<PaymentMethod>,
/// Merchant defined field to reference the transaction.
pub reference: Option<String>,
@@ -55,12 +55,12 @@ pub struct GlobalpayPaymentsResponse {
#[derive(Debug, Serialize, Deserialize)]
pub struct Action {
/// The id of the app that was used to create the token.
- pub app_id: Option<String>,
+ pub app_id: Option<Secret<String>>,
/// The name of the app the user gave to the application.
- pub app_name: Option<String>,
+ pub app_name: Option<Secret<String>>,
/// A unique identifier for the object created by Global Payments. The first 3 characters
/// identifies the resource an id relates to.
- pub id: Option<String>,
+ pub id: Option<Secret<String>>,
/// The result of the action executed.
pub result_code: Option<ResultCode>,
/// Global Payments time indicating when the object was created in ISO-8601 format.
@@ -117,7 +117,7 @@ pub struct PaymentMethod {
/// for that merchant. If the payment method is seen again this same value is generated. For
/// cards the primary account number is checked only. The expiry date or the CVV is not used
/// for this check.
- pub fingerprint: Option<String>,
+ pub fingerprint: Option<Secret<String>>,
/// If enabled, this field indicates whether the payment method has been seen before or is
/// new.
/// * EXISTS - Indicates that the payment method was seen on the platform before by this
@@ -128,7 +128,7 @@ pub struct PaymentMethod {
/// Unique Global Payments generated id used to reference a stored payment method on the
/// Global Payments system. Often referred to as the payment method token. This value can be
/// used instead of payment method details such as a card number and expiry date.
- pub id: Option<String>,
+ pub id: Option<Secret<String>>,
/// Result message from the payment method provider corresponding to the result code.
pub message: Option<String>,
/// Result code from the payment method provider.
@@ -148,7 +148,7 @@ pub struct Apm {
/// transaction.
pub provider: Option<ApmProvider>,
/// A name of the payer from the payment method system.
- pub provider_payer_name: Option<String>,
+ pub provider_payer_name: Option<Secret<String>>,
/// The time the payment method provider created the transaction at on their system.
pub provider_time_created: Option<String>,
/// The reference the payment method provider created for the transaction.
@@ -162,28 +162,28 @@ pub struct Apm {
pub redirect_url: Option<String>,
/// A string generated by the payment method to represent the session created on the payment
/// method's platform to facilitate the creation of a transaction.
- pub session_token: Option<String>,
+ pub session_token: Option<Secret<String>>,
pub payment_description: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Bank {
/// The local identifier of the bank account.
- pub account_number: Option<String>,
+ pub account_number: Option<Secret<String>>,
/// The local identifier of the bank.
- pub code: Option<String>,
+ pub code: Option<Secret<String>>,
/// The international identifier of the bank account.
- pub iban: Option<String>,
+ pub iban: Option<Secret<String>>,
/// The international identifier code for the bank.
- pub identifier_code: Option<String>,
+ pub identifier_code: Option<Secret<String>>,
/// The name associated with the bank account
- pub name: Option<String>,
+ pub name: Option<Secret<String>>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Mandate {
/// The reference to identify the mandate.
- pub code: Option<String>,
+ pub code: Option<Secret<String>>,
}
/// Information outlining the degree of authentication executed related to a transaction.
@@ -205,7 +205,7 @@ pub struct BankTransfer {
/// The last 4 characters of the local reference for a bank account number.
pub masked_number_last4: Option<String>,
/// The name of the bank.
- pub name: Option<String>,
+ pub name: Option<Secret<String>>,
/// The type of bank account associated with the payer's bank account.
pub number_type: Option<NumberType>,
}
@@ -213,7 +213,7 @@ pub struct BankTransfer {
#[derive(Debug, Serialize, Deserialize)]
pub struct Card {
/// Code generated when the card is successfully authorized.
- pub authcode: Option<String>,
+ pub authcode: Option<Secret<String>>,
/// The recommended AVS action to be taken by the agent processing the card transaction.
pub avs_action: Option<String>,
/// The result of the AVS address check.
@@ -223,7 +223,7 @@ pub struct Card {
/// Indicates the card brand that issued the card.
pub brand: Option<Brand>,
/// The unique reference created by the brands/schemes to uniquely identify the transaction.
- pub brand_reference: Option<String>,
+ pub brand_reference: Option<Secret<String>>,
/// The time returned by the card brand indicating when the transaction was processed on
/// their system.
pub brand_time_reference: Option<String>,
@@ -235,7 +235,7 @@ pub struct Card {
pub provider: Option<ProviderClass>,
/// The card EMV tag response data from the card issuer for a contactless or chip card
/// transaction.
- pub tag_response: Option<String>,
+ pub tag_response: Option<Secret<String>>,
}
/// The result codes directly from the card issuer.
diff --git a/crates/router/src/connector/globalpay/transformers.rs b/crates/router/src/connector/globalpay/transformers.rs
index 3124501bd6e..1e410946251 100644
--- a/crates/router/src/connector/globalpay/transformers.rs
+++ b/crates/router/src/connector/globalpay/transformers.rs
@@ -1,6 +1,6 @@
use common_utils::crypto::{self, GenerateDigest};
use error_stack::{IntoReport, ResultExt};
-use masking::{PeekInterface, Secret};
+use masking::{ExposeInterface, PeekInterface, Secret};
use rand::distributions::DistString;
use serde::{Deserialize, Serialize};
use url::Url;
@@ -164,8 +164,8 @@ impl TryFrom<&types::RefreshTokenRouterData> for GlobalpayRefreshTokenRequest {
Ok(Self {
app_id: globalpay_auth.app_id,
- nonce,
- secret,
+ nonce: Secret::new(nonce),
+ secret: Secret::new(secret),
grant_type: "client_credentials".to_string(),
})
}
@@ -215,7 +215,7 @@ fn get_payment_response(
.as_ref()
.and_then(|card| card.brand_reference.to_owned())
.map(|id| types::MandateReference {
- connector_mandate_id: Some(id),
+ connector_mandate_id: Some(id.expose()),
payment_method_id: None,
})
});
|
2024-02-27T07:49:58Z
|
## 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 -->
Mask pii information passed and received in the connector request and response for Globalpay.
## Test Case
1.a. Card Mandate Payment Create
```
{
"amount": 10000,
"currency": "USD",
"confirm": true,
"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": "no_three_ds",
"return_url": "https://hs-payments-test.netlify.app/payments",
"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"
},
"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"
},
"payment_method": "card",
"payment_method_data": {
"card": {
"card_number": "4917 6100 0000 0000",
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": "Joseph Doe",
"card_cvc": "737"
}
},
"setup_future_usage": "off_session",
"mandate_data": {
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "13.232.74.226",
"user_agent": "amet irure esse"
}
}
,
"mandate_type": {
"multi_use": {
"amount": 799,
"currency": "USD"
}
}
}
}
```
1.b. Check if all the sensitive data in the `masked_response` is masked
```
curl --location '{{base_url}}/analytics/v1/connector_event_logs?type=Payment&payment_id={{payment_id}}' \
--header 'sec-ch-ua: "Not A(Brand";v="99", "Google Chrome";v="121", "Chromium";v="121"' \
--header 'sec-ch-ua-mobile: ?0' \
--header 'authorization: Bearer JWT_token' \
--header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36' \
--header 'Content-Type: application/json' \
--header 'Referer: https://integ.hyperswitch.io/' \
--header 'api-key: {{api-key}}' \
--header 'sec-ch-ua-platform: "macOS"'
```
Response - Card Mandate Payment
```
"{\\\"account_id\\\":\\\"*** alloc::string::String ***\\\",\\\"account_name\\\":\\\"*** alloc::string::String ***\\\",\\\"action\\\":{\\\"app_id\\\":\\\"*** alloc::string::String ***\\\",\\\"app_name\\\":\\\"*** alloc::string::String ***\\\",\\\"id\\\":\\\"*** alloc::string::String ***\\\",\\\"result_code\\\":\\\"SUCCESS\\\",\\\"time_created\\\":\\\"2024-02-27T08:01:06.335Z\\\",\\\"type\\\":\\\"AUTHORIZE\\\"},\\\"amount\\\":\\\"10000\\\",\\\"authorization_mode\\\":null,\\\"batch_id\\\":\\\"BAT_1361216\\\",\\\"capture_mode\\\":\\\"AUTO\\\",\\\"channel\\\":\\\"CNP\\\",\\\"country\\\":\\\"US\\\",\\\"currency\\\":\\\"USD\\\",\\\"currency_conversion\\\":{\\\"id\\\":null},\\\"id\\\":\\\"TRN_QkEUmx4RVM2KJuIh1w97WKMkIQVOpg_44PMyDl6oy_1\\\",\\\"merchant_id\\\":\\\"MER_7e3e2c7df34f42819b3edee31022ee3f\\\",\\\"merchant_name\\\":\\\"*** alloc::string::String ***\\\",\\\"payment_method\\\":{\\\"apm\\\":null,\\\"authentication\\\":{\\\"three_ds\\\":null},\\\"bank_transfer\\\":null,\\\"card\\\":{\\\"authcode\\\":\\\"*** alloc::string::String ***\\\",\\\"avs_action\\\":\\\"\\\",\\\"avs_address_result\\\":\\\"NOT_CHECKED\\\",\\\"avs_postal_code_result\\\":\\\"NOT_CHECKED\\\",\\\"brand\\\":\\\"VISA\\\",\\\"brand_reference\\\":\\\"*** alloc::string::String ***\\\",\\\"brand_time_reference\\\":null,\\\"cvv_result\\\":\\\"NOT_CHECKED\\\",\\\"masked_number_last4\\\":\\\"*** alloc::string::String ***\\\",\\\"provider\\\":{\\\"card.provider.avs_address_result\\\":null,\\\"card.provider.avs_postal_code_result\\\":null,\\\"card.provider.avs_result\\\":null,\\\"card.provider.cvv_result\\\":null,\\\"card.provider.result\\\":null},\\\"tag_response\\\":\\\"*** alloc::string::String ***\\\"},\\\"digital_wallet\\\":null,\\\"entry_mode\\\":\\\"ECOM\\\",\\\"fingerprint\\\":null,\\\"fingerprint_presence_indicator\\\":null,\\\"id\\\":null,\\\"message\\\":\\\"[ test system ] Authorised\\\",\\\"result\\\":\\\"00\\\"},\\\"reference\\\":\\\"pay_zaVdoNy0DL44PMyDl6oy_1\\\",\\\"status\\\":\\\"CAPTURED\\\",\\\"time_created\\\":\\\"2024-02-27T08:01:06.335Z\\\",\\\"type\\\":\\\"SALE\\\"}
```
_Note: A know bug in recurring mandate payments_
## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
2b0fbc70749338d5c501bbb782d6fc4747890d61
|
|
juspay/hyperswitch
|
juspay__hyperswitch-3823
|
Bug: [FIX] add unit tests to check backwards compatibility of KV types
|
diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rs
index 927a05bfa56..cc4f3e5a89a 100644
--- a/crates/diesel_models/src/payment_attempt.rs
+++ b/crates/diesel_models/src/payment_attempt.rs
@@ -776,3 +776,100 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
}
}
}
+
+mod tests {
+
+ #[test]
+ fn test_backwards_compatibility() {
+ let serialized_payment_attempt = r#"{
+ "id": 1,
+ "payment_id": "PMT123456789",
+ "merchant_id": "M123456789",
+ "attempt_id": "ATMPT123456789",
+ "status": "pending",
+ "amount": 10000,
+ "currency": "USD",
+ "save_to_locker": true,
+ "connector": "stripe",
+ "error_message": null,
+ "offer_amount": 9500,
+ "surcharge_amount": 500,
+ "tax_amount": 800,
+ "payment_method_id": "CRD123456789",
+ "payment_method": "card",
+ "connector_transaction_id": "CNTR123456789",
+ "capture_method": "automatic",
+ "capture_on": "2022-09-10T10:11:12Z",
+ "confirm": false,
+ "authentication_type": "no_three_ds",
+ "created_at": "2024-02-26T12:00:00Z",
+ "modified_at": "2024-02-26T12:00:00Z",
+ "last_synced": null,
+ "cancellation_reason": null,
+ "amount_to_capture": 10000,
+ "mandate_id": null,
+ "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"
+ },
+ "error_code": null,
+ "payment_token": "TOKEN123456789",
+ "connector_metadata": null,
+ "payment_experience": "redirect_to_url",
+ "payment_method_type": "credit",
+ "payment_method_data": {
+ "card": {
+ "card_number": "4242424242424242",
+ "card_exp_month": "10",
+ "card_cvc": "123",
+ "card_exp_year": "2024",
+ "card_holder_name": "John Doe"
+ }
+ },
+ "business_sub_label": "Premium",
+ "straight_through_algorithm": null,
+ "preprocessing_step_id": null,
+ "mandate_details": null,
+ "error_reason": null,
+ "multiple_capture_count": 0,
+ "connector_response_reference_id": null,
+ "amount_capturable": 10000,
+ "updated_by": "redis_kv",
+ "merchant_connector_id": "MCN123456789",
+ "authentication_data": null,
+ "encoded_data": null,
+ "unified_code": null,
+ "unified_message": null,
+ "net_amount": 10200,
+ "mandate_data": {
+ "customer_acceptance": {
+ "acceptance_type": "offline",
+ "accepted_at": "1963-05-03T04:07:52.723Z",
+ "online": {
+ "ip_address": "127.0.0.1",
+ "user_agent": "amet irure esse"
+ }
+ },
+ "mandate_type": {
+ "single_use": {
+ "amount": 6540,
+ "currency": "USD"
+ }
+ }
+},
+ "fingerprint_id": null
+}"#;
+ let deserialized =
+ serde_json::from_str::<super::PaymentAttempt>(serialized_payment_attempt);
+
+ assert!(deserialized.is_ok());
+ }
+}
diff --git a/crates/diesel_models/src/payment_intent.rs b/crates/diesel_models/src/payment_intent.rs
index 69fb61a8d42..b14554e3032 100644
--- a/crates/diesel_models/src/payment_intent.rs
+++ b/crates/diesel_models/src/payment_intent.rs
@@ -485,3 +485,56 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {
}
}
}
+
+mod tests {
+ #[test]
+ fn test_backwards_compatibility() {
+ let serialized_payment_intent = r#"{
+ "id": 123,
+ "payment_id": "payment_12345",
+ "merchant_id": "merchant_67890",
+ "status": "succeeded",
+ "amount": 10000,
+ "currency": "USD",
+ "amount_captured": null,
+ "customer_id": "cust_123456",
+ "description": "Test Payment",
+ "return_url": "https://example.com/return",
+ "metadata": null,
+ "connector_id": "connector_001",
+ "shipping_address_id": null,
+ "billing_address_id": null,
+ "statement_descriptor_name": null,
+ "statement_descriptor_suffix": null,
+ "created_at": "2024-02-01T12:00:00Z",
+ "modified_at": "2024-02-01T12:00:00Z",
+ "last_synced": null,
+ "setup_future_usage": null,
+ "off_session": null,
+ "client_secret": "sec_abcdef1234567890",
+ "active_attempt_id": "attempt_123",
+ "business_country": "US",
+ "business_label": null,
+ "order_details": null,
+ "allowed_payment_method_types": "credit",
+ "connector_metadata": null,
+ "feature_metadata": null,
+ "attempt_count": 1,
+ "profile_id": null,
+ "merchant_decision": null,
+ "payment_link_id": null,
+ "payment_confirm_source": null,
+ "updated_by": "admin",
+ "surcharge_applicable": null,
+ "request_incremental_authorization": null,
+ "incremental_authorization_allowed": null,
+ "authorization_count": null,
+ "session_expiry": null,
+ "fingerprint_id": null
+}"#;
+ let deserialized_payment_intent =
+ serde_json::from_str::<super::PaymentIntent>(serialized_payment_intent);
+
+ assert!(deserialized_payment_intent.is_ok());
+ }
+}
diff --git a/crates/diesel_models/src/refund.rs b/crates/diesel_models/src/refund.rs
index bb805fb646c..0ee486bae48 100644
--- a/crates/diesel_models/src/refund.rs
+++ b/crates/diesel_models/src/refund.rs
@@ -244,3 +244,41 @@ impl common_utils::events::ApiEventMetric for Refund {
})
}
}
+
+mod tests {
+ #[test]
+ fn test_backwards_compatibility() {
+ let serialized_refund = r#"{
+ "id": 1,
+ "internal_reference_id": "internal_ref_123",
+ "refund_id": "refund_456",
+ "payment_id": "payment_789",
+ "merchant_id": "merchant_123",
+ "connector_transaction_id": "connector_txn_789",
+ "connector": "stripe",
+ "connector_refund_id": null,
+ "external_reference_id": null,
+ "refund_type": "instant_refund",
+ "total_amount": 10000,
+ "currency": "USD",
+ "refund_amount": 9500,
+ "refund_status": "Success",
+ "sent_to_gateway": true,
+ "refund_error_message": null,
+ "metadata": null,
+ "refund_arn": null,
+ "created_at": "2024-02-26T12:00:00Z",
+ "updated_at": "2024-02-26T12:00:00Z",
+ "description": null,
+ "attempt_id": "attempt_123",
+ "refund_reason": null,
+ "refund_error_code": null,
+ "profile_id": null,
+ "updated_by": "admin",
+ "merchant_connector_id": null
+}"#;
+ let deserialized = serde_json::from_str::<super::Refund>(serialized_refund);
+
+ assert!(deserialized.is_ok());
+ }
+}
|
2024-02-26T10:51:09Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [x] Enhancement
## Description
<!-- Describe your changes in detail -->
Add Unit tests for testing backwards compatibility
## 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 tests if the type is backwards compatible or not
## 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)?
-->
## Local Testing
- Run `cargo tests --all-features -p diesel_models` it should pass all tests
## Sandbox
- Cannot be tested in 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
|
75c633fc7c37341177597041ccbcdfc3cf9e236f
|
|
juspay/hyperswitch
|
juspay__hyperswitch-3825
|
Bug: [FEATURE] : [Forte] mask pii information in connector request and response
### Feature Description
Mask pii information passed and received in the connector request and response
### Possible Implementation
Refactor all sensitive response and request fields secret
### 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/forte/transformers.rs b/crates/router/src/connector/forte/transformers.rs
index 83bcb2c551b..00efbefe287 100644
--- a/crates/router/src/connector/forte/transformers.rs
+++ b/crates/router/src/connector/forte/transformers.rs
@@ -240,7 +240,7 @@ pub enum ForteAction {
#[derive(Debug, Deserialize, Serialize)]
pub struct FortePaymentsResponse {
pub transaction_id: String,
- pub location_id: String,
+ pub location_id: Secret<String>,
pub action: ForteAction,
pub authorization_amount: Option<f64>,
pub authorization_code: String,
@@ -289,7 +289,7 @@ impl<F, T>
#[derive(Debug, Deserialize, Serialize)]
pub struct FortePaymentsSyncResponse {
pub transaction_id: String,
- pub location_id: String,
+ pub location_id: Secret<String>,
pub status: FortePaymentStatus,
pub action: ForteAction,
pub authorization_amount: Option<f64>,
@@ -434,7 +434,7 @@ pub struct CancelResponseStatus {
#[derive(Debug, Deserialize, Serialize)]
pub struct ForteCancelResponse {
pub transaction_id: String,
- pub location_id: String,
+ pub location_id: Secret<String>,
pub action: String,
pub authorization_code: String,
pub entered_by: String,
|
2024-02-26T11:15:49Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [x] New feature
- [x] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Describe your changes in detail -->
Mask pii information passed and received in the connector request and response for Forte.
## Test Case
<!--
Did you write an integration/unit/API test to verify the code changes?
Or did you test this change manually (provide relevant screenshots)?
-->
1.a.1 Card Payment
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_LQJkIZUCjJegIRLaclDqzXFZi5g76kp3AjfZ18bxUroPYL9iTNqSbMTiNkvzTO62' \
--data-raw '{
"amount": 2000,
"currency": "USD",
"confirm": true,
"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": "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"
}
},
"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"
},
"payment_method": "card",
"payment_method_data": {
"card": {
"card_number": "4111111111111111",
"card_exp_month": "10",
"card_exp_year": "30",
"card_holder_name": "Joseph Doe",
"card_cvc": "123"
}
}
}'
```
1.a.2. Psync
```
curl --location 'http://localhost:8080/payments/pay_m55biPPvXK58EXXDzViv?expand_captures=true' \
--header 'Accept: application/json' \
--header 'api-key:{{api_key}}'
```
1.b. Check if all the sensitive data in the `masked_response` is masked
```
curl --location '{{base_url}}/analytics/v1/connector_event_logs?type=Payment&payment_id={{payment_id}}' \
--header 'sec-ch-ua: "Not A(Brand";v="99", "Google Chrome";v="121", "Chromium";v="121"' \
--header 'sec-ch-ua-mobile: ?0' \
--header 'authorization: Bearer JWT_token' \
--header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36' \
--header 'Content-Type: application/json' \
--header 'Referer: https://integ.hyperswitch.io/' \
--header 'api-key: {{api-key}}' \
--header 'sec-ch-ua-platform: "macOS"'
```
masked_response should be
```
"masked_response":\"{\\\"transaction_id\\\":\\\"trn_2d204ee6-263a-4f4f-9a52-42f66b899583\\\",\\\"location_id\\\":\\\"*** alloc::string::String ***\\\",\\\"action\\\":\\\"sale\\\",\\\"authorization_amount\\\":20.0,\\\"authorization_code\\\":\\\"6QL672\\\",\\\"entered_by\\\":\\\"0ec774886e654a66c2e46854b0f4f002\\\",\\\"billing_address\\\":{\\\"first_name\\\":\\\"*** alloc::string::String ***\\\",\\\"last_name\\\":\\\"*** alloc::string::String ***\\\"},\\\"card\\\":{\\\"name_on_card\\\":\\\"*** alloc::string::String ***\\\",\\\"last_4_account_number\\\":\\\"1111\\\",\\\"masked_account_number\\\":\\\"****1111\\\",\\\"card_type\\\":\\\"visa\\\"},\\\"response\\\":{\\\"environment\\\":\\\"sandbox\\\",\\\"response_type\\\":\\\"A\\\",\\\"response_code\\\":\\\"A01\\\",\\\"response_desc\\\":\\\"TEST APPROVAL\\\",\\\"authorization_code\\\":\\\"6QL672\\\",\\\"avs_result\\\":\\\"Y\\\",\\\"cvv_result\\\":\\\"M\\\"}}\",\"error\":null,\"url\":\"https://sandbox.forte.net/api/v3/organizations/org_438530/locations/loc_316671/transactions\",\"method\":\"POST\",\"payment_id\":\"pay_weAKeLQvLWQuRZpDrV76\",\"merchant_id\":\"merchant_1708944415\",\"created_at\":1708945666007,\"request_id\":\"018de519-66d7-71ff-b05b-c50d3ac3b156\",\"latency\":1515,\"refund_id\":null,\"dispute_id\":null,\"status_code\":201}
```
2.a Void a transaction
2.a.1 Auth a transaction
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key:{{api-key}}' \
--data-raw '{
"amount": 2000,
"currency": "USD",
"confirm": true,
"capture_method": "manual",
"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://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"
}
},
"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"
},
"payment_method": "card",
"payment_method_data": {
"card": {
"card_number": "4111111111111111",
"card_exp_month": "10",
"card_exp_year": "30",
"card_holder_name": "Joseph Doe",
"card_cvc": "123"
}
}
}'
```
2.a.2 Void the payment
```
curl --location 'http://localhost:8080/payments/pay_m55biPPvXK58EXXDzViv/cancel' \
--header 'Content-Type: application/json' \
--header 'api-key:{{api_key}}' \
--data '{
"cancellation_reason": "requested_by_customer"
}'
```
1.b. Check if all the sensitive data in the `masked_response` is masked. In logs check for
`topic = "hyperswitch-outgoing-connector-events" `
## Impacted Area
> Card Payment
> Payment Sync
> Payment Cancel
## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
75c633fc7c37341177597041ccbcdfc3cf9e236f
|
|
juspay/hyperswitch
|
juspay__hyperswitch-3836
|
Bug: feat: change list roles, get role, info api to respond with groups
|
diff --git a/crates/api_models/src/events/user_role.rs b/crates/api_models/src/events/user_role.rs
index f19ff95f9ed..f46c5cf312b 100644
--- a/crates/api_models/src/events/user_role.rs
+++ b/crates/api_models/src/events/user_role.rs
@@ -2,15 +2,15 @@ use common_utils::events::{ApiEventMetric, ApiEventsType};
use crate::user_role::{
role::{
- CreateRoleRequest, GetRoleRequest, ListRolesResponse, RoleInfoResponse, UpdateRoleRequest,
+ CreateRoleRequest, GetRoleRequest, ListRolesResponse, RoleInfoResponse,
+ RoleInfoWithPermissionsResponse, UpdateRoleRequest,
},
AcceptInvitationRequest, AuthorizationInfoResponse, DeleteUserRoleRequest,
TransferOrgOwnershipRequest, UpdateUserRoleRequest,
};
common_utils::impl_misc_api_event_type!(
- ListRolesResponse,
- RoleInfoResponse,
+ RoleInfoWithPermissionsResponse,
GetRoleRequest,
AuthorizationInfoResponse,
UpdateUserRoleRequest,
@@ -18,5 +18,7 @@ common_utils::impl_misc_api_event_type!(
DeleteUserRoleRequest,
TransferOrgOwnershipRequest,
CreateRoleRequest,
- UpdateRoleRequest
+ UpdateRoleRequest,
+ ListRolesResponse,
+ RoleInfoResponse
);
diff --git a/crates/api_models/src/user_role.rs b/crates/api_models/src/user_role.rs
index ed0838adc24..80d3861969a 100644
--- a/crates/api_models/src/user_role.rs
+++ b/crates/api_models/src/user_role.rs
@@ -1,3 +1,4 @@
+use common_enums::PermissionGroup;
use common_utils::pii;
use crate::user::DashboardEntryResponse;
@@ -51,7 +52,14 @@ pub enum PermissionModule {
}
#[derive(Debug, serde::Serialize)]
-pub struct AuthorizationInfoResponse(pub Vec<ModuleInfo>);
+pub struct AuthorizationInfoResponse(pub Vec<AuthorizationInfo>);
+
+#[derive(Debug, serde::Serialize)]
+#[serde(untagged)]
+pub enum AuthorizationInfo {
+ Module(ModuleInfo),
+ Group(GroupInfo),
+}
#[derive(Debug, serde::Serialize)]
pub struct ModuleInfo {
@@ -60,6 +68,13 @@ pub struct ModuleInfo {
pub permissions: Vec<PermissionInfo>,
}
+#[derive(Debug, serde::Serialize)]
+pub struct GroupInfo {
+ pub group: PermissionGroup,
+ pub description: &'static str,
+ pub permissions: Vec<PermissionInfo>,
+}
+
#[derive(Debug, serde::Serialize)]
pub struct PermissionInfo {
pub enum_name: Permission,
diff --git a/crates/api_models/src/user_role/role.rs b/crates/api_models/src/user_role/role.rs
index 4a767cfa723..fafb8fede0b 100644
--- a/crates/api_models/src/user_role/role.rs
+++ b/crates/api_models/src/user_role/role.rs
@@ -1,5 +1,7 @@
use common_enums::{PermissionGroup, RoleScope};
+use super::Permission;
+
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct CreateRoleRequest {
pub role_name: String,
@@ -16,10 +18,30 @@ pub struct UpdateRoleRequest {
#[derive(Debug, serde::Serialize)]
pub struct ListRolesResponse(pub Vec<RoleInfoResponse>);
+#[derive(Debug, serde::Deserialize)]
+pub struct GetGroupsQueryParam {
+ pub groups: Option<bool>,
+}
+
#[derive(Debug, serde::Serialize)]
-pub struct RoleInfoResponse {
+#[serde(untagged)]
+pub enum RoleInfoResponse {
+ Permissions(RoleInfoWithPermissionsResponse),
+ Groups(RoleInfoWithGroupsResponse),
+}
+
+#[derive(Debug, serde::Serialize)]
+pub struct RoleInfoWithPermissionsResponse {
pub role_id: String,
- pub permissions: Vec<super::Permission>,
+ pub permissions: Vec<Permission>,
+ pub role_name: String,
+ pub role_scope: RoleScope,
+}
+
+#[derive(Debug, serde::Serialize)]
+pub struct RoleInfoWithGroupsResponse {
+ pub role_id: String,
+ pub groups: Vec<PermissionGroup>,
pub role_name: String,
pub role_scope: RoleScope,
}
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index b8168fc5329..4a87d0c256f 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -2197,6 +2197,7 @@ pub enum RoleScope {
serde::Deserialize,
strum::Display,
strum::EnumString,
+ strum::EnumIter,
)]
#[router_derive::diesel_enum(storage_type = "text")]
#[serde(rename_all = "snake_case")]
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index b38faa34554..b8b8cbd24c7 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -442,7 +442,7 @@ pub async fn invite_user(
.into());
}
- let role_info = roles::get_role_info_from_role_id(
+ let role_info = roles::RoleInfo::from_role_id(
&state,
&request.role_id,
&user_from_token.merchant_id,
@@ -659,7 +659,7 @@ async fn handle_invitation(
.into());
}
- let role_info = roles::get_role_info_from_role_id(
+ let role_info = roles::RoleInfo::from_role_id(
state,
&request.role_id,
&user_from_token.merchant_id,
@@ -1054,7 +1054,7 @@ pub async fn switch_merchant_id(
let user = user_from_token.get_user_from_db(&state).await?;
- let role_info = roles::get_role_info_from_role_id(
+ let role_info = roles::RoleInfo::from_role_id(
&state,
&user_from_token.role_id,
&user_from_token.merchant_id,
@@ -1207,7 +1207,7 @@ pub async fn get_users_for_merchant_account(
let users_user_roles_and_roles =
futures::future::try_join_all(users_and_user_roles.into_iter().map(
|(user, user_role)| async {
- roles::get_role_info_from_role_id(
+ roles::RoleInfo::from_role_id(
&state,
&user_role.role_id,
&user_role.merchant_id,
diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs
index b954e0df6c6..9dca9b43d96 100644
--- a/crates/router/src/core/user_role.rs
+++ b/crates/router/src/core/user_role.rs
@@ -19,14 +19,28 @@ use crate::{
pub mod role;
-pub async fn get_authorization_info(
+// TODO: To be deprecated once groups are stable
+pub async fn get_authorization_info_with_modules(
_state: AppState,
) -> UserResponse<user_role_api::AuthorizationInfoResponse> {
Ok(ApplicationResponse::Json(
user_role_api::AuthorizationInfoResponse(
- info::get_authorization_info()
+ info::get_module_authorization_info()
.into_iter()
- .map(Into::into)
+ .map(|module_info| user_role_api::AuthorizationInfo::Module(module_info.into()))
+ .collect(),
+ ),
+ ))
+}
+
+pub async fn get_authorization_info_with_groups(
+ _state: AppState,
+) -> UserResponse<user_role_api::AuthorizationInfoResponse> {
+ Ok(ApplicationResponse::Json(
+ user_role_api::AuthorizationInfoResponse(
+ info::get_group_authorization_info()
+ .into_iter()
+ .map(user_role_api::AuthorizationInfo::Group)
.collect(),
),
))
@@ -37,7 +51,7 @@ pub async fn update_user_role(
user_from_token: auth::UserFromToken,
req: user_role_api::UpdateUserRoleRequest,
) -> UserResponse<()> {
- let role_info = roles::get_role_info_from_role_id(
+ let role_info = roles::RoleInfo::from_role_id(
&state,
&req.role_id,
&user_from_token.merchant_id,
@@ -67,7 +81,7 @@ pub async fn update_user_role(
.await
.to_not_found_response(UserErrors::InvalidRoleOperation)?;
- let role_to_be_updated = roles::get_role_info_from_role_id(
+ let role_to_be_updated = roles::RoleInfo::from_role_id(
&state,
&user_role_to_be_updated.role_id,
&user_from_token.merchant_id,
@@ -236,7 +250,7 @@ pub async fn delete_user_role(
.find(|&role| role.merchant_id == user_from_token.merchant_id.as_str())
{
Some(user_role) => {
- let role_info = roles::get_role_info_from_role_id(
+ let role_info = roles::RoleInfo::from_role_id(
&state,
&user_role.role_id,
&user_from_token.merchant_id,
diff --git a/crates/router/src/core/user_role/role.rs b/crates/router/src/core/user_role/role.rs
index 6edbda85bfd..cc31798bd8b 100644
--- a/crates/router/src/core/user_role/role.rs
+++ b/crates/router/src/core/user_role/role.rs
@@ -86,22 +86,25 @@ pub async fn create_role(
Ok(ApplicationResponse::StatusOk)
}
-pub async fn list_invitable_roles(
+// TODO: To be deprecated once groups are stable
+pub async fn list_invitable_roles_with_permissions(
state: AppState,
user_from_token: UserFromToken,
) -> UserResponse<role_api::ListRolesResponse> {
let predefined_roles_map = PREDEFINED_ROLES
.iter()
.filter(|(_, role_info)| role_info.is_invitable())
- .map(|(role_id, role_info)| role_api::RoleInfoResponse {
- permissions: role_info
- .get_permissions_set()
- .into_iter()
- .map(Into::into)
- .collect(),
- role_id: role_id.to_string(),
- role_name: role_info.get_role_name().to_string(),
- role_scope: role_info.get_scope(),
+ .map(|(role_id, role_info)| {
+ role_api::RoleInfoResponse::Permissions(role_api::RoleInfoWithPermissionsResponse {
+ permissions: role_info
+ .get_permissions_set()
+ .into_iter()
+ .map(Into::into)
+ .collect(),
+ role_id: role_id.to_string(),
+ role_name: role_info.get_role_name().to_string(),
+ role_scope: role_info.get_scope(),
+ })
});
let custom_roles_map = state
@@ -110,17 +113,22 @@ pub async fn list_invitable_roles(
.await
.change_context(UserErrors::InternalServerError)?
.into_iter()
- .map(roles::RoleInfo::from)
- .filter(|role_info| role_info.is_invitable())
- .map(|role_info| role_api::RoleInfoResponse {
- permissions: role_info
- .get_permissions_set()
- .into_iter()
- .map(Into::into)
- .collect(),
- role_id: role_info.get_role_id().to_string(),
- role_name: role_info.get_role_name().to_string(),
- role_scope: role_info.get_scope(),
+ .filter_map(|role| {
+ let role_info = roles::RoleInfo::from(role);
+ role_info
+ .is_invitable()
+ .then_some(role_api::RoleInfoResponse::Permissions(
+ role_api::RoleInfoWithPermissionsResponse {
+ permissions: role_info
+ .get_permissions_set()
+ .into_iter()
+ .map(Into::into)
+ .collect(),
+ role_id: role_info.get_role_id().to_string(),
+ role_name: role_info.get_role_name().to_string(),
+ role_scope: role_info.get_scope(),
+ },
+ ))
});
Ok(ApplicationResponse::Json(role_api::ListRolesResponse(
@@ -128,12 +136,54 @@ pub async fn list_invitable_roles(
)))
}
-pub async fn get_role(
+pub async fn list_invitable_roles_with_groups(
+ state: AppState,
+ user_from_token: UserFromToken,
+) -> UserResponse<role_api::ListRolesResponse> {
+ let predefined_roles_map = PREDEFINED_ROLES
+ .iter()
+ .filter(|(_, role_info)| role_info.is_invitable())
+ .map(|(role_id, role_info)| {
+ role_api::RoleInfoResponse::Groups(role_api::RoleInfoWithGroupsResponse {
+ groups: role_info.get_permission_groups().to_vec(),
+ role_id: role_id.to_string(),
+ role_name: role_info.get_role_name().to_string(),
+ role_scope: role_info.get_scope(),
+ })
+ });
+
+ let custom_roles_map = state
+ .store
+ .list_all_roles(&user_from_token.merchant_id, &user_from_token.org_id)
+ .await
+ .change_context(UserErrors::InternalServerError)?
+ .into_iter()
+ .filter_map(|role| {
+ let role_info = roles::RoleInfo::from(role);
+ role_info
+ .is_invitable()
+ .then_some(role_api::RoleInfoResponse::Groups(
+ role_api::RoleInfoWithGroupsResponse {
+ groups: role_info.get_permission_groups().to_vec(),
+ role_id: role_info.get_role_id().to_string(),
+ role_name: role_info.get_role_name().to_string(),
+ role_scope: role_info.get_scope(),
+ },
+ ))
+ });
+
+ Ok(ApplicationResponse::Json(role_api::ListRolesResponse(
+ predefined_roles_map.chain(custom_roles_map).collect(),
+ )))
+}
+
+// TODO: To be deprecated once groups are stable
+pub async fn get_role_with_permissions(
state: AppState,
user_from_token: UserFromToken,
role: role_api::GetRoleRequest,
) -> UserResponse<role_api::RoleInfoResponse> {
- let role_info = roles::get_role_info_from_role_id(
+ let role_info = roles::RoleInfo::from_role_id(
&state,
&role.role_id,
&user_from_token.merchant_id,
@@ -152,12 +202,42 @@ pub async fn get_role(
.map(Into::into)
.collect();
- Ok(ApplicationResponse::Json(role_api::RoleInfoResponse {
- permissions,
- role_id: role.role_id,
- role_name: role_info.get_role_name().to_string(),
- role_scope: role_info.get_scope(),
- }))
+ Ok(ApplicationResponse::Json(
+ role_api::RoleInfoResponse::Permissions(role_api::RoleInfoWithPermissionsResponse {
+ permissions,
+ role_id: role.role_id,
+ role_name: role_info.get_role_name().to_string(),
+ role_scope: role_info.get_scope(),
+ }),
+ ))
+}
+
+pub async fn get_role_with_groups(
+ state: AppState,
+ user_from_token: UserFromToken,
+ role: role_api::GetRoleRequest,
+) -> UserResponse<role_api::RoleInfoResponse> {
+ let role_info = roles::RoleInfo::from_role_id(
+ &state,
+ &role.role_id,
+ &user_from_token.merchant_id,
+ &user_from_token.org_id,
+ )
+ .await
+ .to_not_found_response(UserErrors::InvalidRoleId)?;
+
+ if role_info.is_internal() {
+ return Err(UserErrors::InvalidRoleId.into());
+ }
+
+ Ok(ApplicationResponse::Json(
+ role_api::RoleInfoResponse::Groups(role_api::RoleInfoWithGroupsResponse {
+ groups: role_info.get_permission_groups().to_vec(),
+ role_id: role.role_id,
+ role_name: role_info.get_role_name().to_string(),
+ role_scope: role_info.get_scope(),
+ }),
+ ))
}
pub async fn update_role(
@@ -182,7 +262,7 @@ pub async fn update_role(
.await?;
}
- let role_info = roles::get_role_info_from_role_id(
+ let role_info = roles::RoleInfo::from_role_id(
&state,
role_id,
&user_from_token.merchant_id,
diff --git a/crates/router/src/routes/user_role.rs b/crates/router/src/routes/user_role.rs
index 52e739c36e1..75de9e7e6f7 100644
--- a/crates/router/src/routes/user_role.rs
+++ b/crates/router/src/routes/user_role.rs
@@ -1,10 +1,13 @@
use actix_web::{web, HttpRequest, HttpResponse};
-use api_models::user_role as user_role_api;
+use api_models::user_role::{self as user_role_api, role as role_api};
use router_env::Flow;
use super::AppState;
use crate::{
- core::{api_locking, user_role as user_role_core},
+ core::{
+ api_locking,
+ user_role::{self as user_role_core, role as role_core},
+ },
services::{
api,
authentication::{self as auth},
@@ -15,14 +18,23 @@ use crate::{
pub async fn get_authorization_info(
state: web::Data<AppState>,
http_req: HttpRequest,
+ query: web::Query<role_api::GetGroupsQueryParam>,
) -> HttpResponse {
let flow = Flow::GetAuthorizationInfo;
+ let respond_with_groups = query.into_inner().groups.unwrap_or(false);
Box::pin(api::server_wrap(
flow,
state.clone(),
&http_req,
(),
- |state, _: (), _| user_role_core::get_authorization_info(state),
+ |state, _: (), _| async move {
+ // TODO: Permissions to be deprecated once groups are stable
+ if respond_with_groups {
+ user_role_core::get_authorization_info_with_groups(state).await
+ } else {
+ user_role_core::get_authorization_info_with_modules(state).await
+ }
+ },
&auth::JWTAuth(Permission::UsersRead),
api_locking::LockAction::NotApplicable,
))
@@ -36,7 +48,7 @@ pub async fn get_role_from_token(state: web::Data<AppState>, req: HttpRequest) -
state.clone(),
&req,
(),
- |state, user, _| user_role_core::role::get_role_from_token(state, user),
+ |state, user, _| role_core::get_role_from_token(state, user),
&auth::DashboardNoPermissionAuth,
api_locking::LockAction::NotApplicable,
))
@@ -46,7 +58,7 @@ pub async fn get_role_from_token(state: web::Data<AppState>, req: HttpRequest) -
pub async fn create_role(
state: web::Data<AppState>,
req: HttpRequest,
- json_payload: web::Json<user_role_api::role::CreateRoleRequest>,
+ json_payload: web::Json<role_api::CreateRoleRequest>,
) -> HttpResponse {
let flow = Flow::CreateRole;
Box::pin(api::server_wrap(
@@ -54,21 +66,33 @@ pub async fn create_role(
state.clone(),
&req,
json_payload.into_inner(),
- user_role_core::role::create_role,
+ role_core::create_role,
&auth::JWTAuth(Permission::UsersWrite),
api_locking::LockAction::NotApplicable,
))
.await
}
-pub async fn list_all_roles(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse {
+pub async fn list_all_roles(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ query: web::Query<role_api::GetGroupsQueryParam>,
+) -> HttpResponse {
let flow = Flow::ListRoles;
+ let respond_with_groups = query.into_inner().groups.unwrap_or(false);
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
(),
- |state, user, _| user_role_core::role::list_invitable_roles(state, user),
+ |state, user, _| async move {
+ // TODO: Permissions to be deprecated once groups are stable
+ if respond_with_groups {
+ role_core::list_invitable_roles_with_groups(state, user).await
+ } else {
+ role_core::list_invitable_roles_with_permissions(state, user).await
+ }
+ },
&auth::JWTAuth(Permission::UsersRead),
api_locking::LockAction::NotApplicable,
))
@@ -79,17 +103,26 @@ pub async fn get_role(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
+ query: web::Query<role_api::GetGroupsQueryParam>,
) -> HttpResponse {
let flow = Flow::GetRole;
let request_payload = user_role_api::role::GetRoleRequest {
role_id: path.into_inner(),
};
+ let respond_with_groups = query.into_inner().groups.unwrap_or(false);
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
request_payload,
- user_role_core::role::get_role,
+ |state, user, payload| async move {
+ // TODO: Permissions to be deprecated once groups are stable
+ if respond_with_groups {
+ role_core::get_role_with_groups(state, user, payload).await
+ } else {
+ role_core::get_role_with_permissions(state, user, payload).await
+ }
+ },
&auth::JWTAuth(Permission::UsersRead),
api_locking::LockAction::NotApplicable,
))
@@ -99,7 +132,7 @@ pub async fn get_role(
pub async fn update_role(
state: web::Data<AppState>,
req: HttpRequest,
- json_payload: web::Json<user_role_api::role::UpdateRoleRequest>,
+ json_payload: web::Json<role_api::UpdateRoleRequest>,
path: web::Path<String>,
) -> HttpResponse {
let flow = Flow::UpdateRole;
@@ -110,7 +143,7 @@ pub async fn update_role(
state.clone(),
&req,
json_payload.into_inner(),
- |state, user, req| user_role_core::role::update_role(state, user, req, &role_id),
+ |state, user, req| role_core::update_role(state, user, req, &role_id),
&auth::JWTAuth(Permission::UsersWrite),
api_locking::LockAction::NotApplicable,
))
diff --git a/crates/router/src/services/authorization.rs b/crates/router/src/services/authorization.rs
index 034773a07ea..2a516cc82d5 100644
--- a/crates/router/src/services/authorization.rs
+++ b/crates/router/src/services/authorization.rs
@@ -6,6 +6,7 @@ use crate::{
routes::app::AppStateInfo,
};
+#[cfg(feature = "olap")]
pub mod info;
pub mod permission_groups;
pub mod permissions;
diff --git a/crates/router/src/services/authorization/info.rs b/crates/router/src/services/authorization/info.rs
index d982317e023..d6a20b7f8ed 100644
--- a/crates/router/src/services/authorization/info.rs
+++ b/crates/router/src/services/authorization/info.rs
@@ -1,30 +1,32 @@
+use api_models::user_role::{GroupInfo, PermissionInfo};
+use common_enums::PermissionGroup;
use strum::{EnumIter, IntoEnumIterator};
-use super::permissions::Permission;
+use super::{permission_groups::get_permissions_vec, permissions::Permission};
-pub fn get_authorization_info() -> Vec<ModuleInfo> {
+pub fn get_module_authorization_info() -> Vec<ModuleInfo> {
PermissionModule::iter()
.map(|module| ModuleInfo::new(&module))
.collect()
}
-pub struct PermissionInfo {
- pub enum_name: Permission,
- pub description: &'static str,
+pub fn get_group_authorization_info() -> Vec<GroupInfo> {
+ PermissionGroup::iter()
+ .map(get_group_info_from_permission_group)
+ .collect()
}
-impl PermissionInfo {
- pub fn new(permissions: &[Permission]) -> Vec<Self> {
- permissions
- .iter()
- .map(|&per| Self {
- description: Permission::get_permission_description(&per),
- enum_name: per,
- })
- .collect()
- }
+pub fn get_permission_info_from_permissions(permissions: &[Permission]) -> Vec<PermissionInfo> {
+ permissions
+ .iter()
+ .map(|&per| PermissionInfo {
+ description: Permission::get_permission_description(&per),
+ enum_name: per.into(),
+ })
+ .collect()
}
+// TODO: Deprecate once groups are stable
#[derive(PartialEq, EnumIter, Clone)]
pub enum PermissionModule {
Payments,
@@ -60,6 +62,7 @@ impl PermissionModule {
}
}
+// TODO: Deprecate once groups are stable
pub struct ModuleInfo {
pub module: PermissionModule,
pub description: &'static str,
@@ -75,7 +78,7 @@ impl ModuleInfo {
PermissionModule::Payments => Self {
module: module_name,
description,
- permissions: PermissionInfo::new(&[
+ permissions: get_permission_info_from_permissions(&[
Permission::PaymentRead,
Permission::PaymentWrite,
]),
@@ -83,7 +86,7 @@ impl ModuleInfo {
PermissionModule::Refunds => Self {
module: module_name,
description,
- permissions: PermissionInfo::new(&[
+ permissions: get_permission_info_from_permissions(&[
Permission::RefundRead,
Permission::RefundWrite,
]),
@@ -91,7 +94,7 @@ impl ModuleInfo {
PermissionModule::MerchantAccount => Self {
module: module_name,
description,
- permissions: PermissionInfo::new(&[
+ permissions: get_permission_info_from_permissions(&[
Permission::MerchantAccountRead,
Permission::MerchantAccountWrite,
]),
@@ -99,7 +102,7 @@ impl ModuleInfo {
PermissionModule::Connectors => Self {
module: module_name,
description,
- permissions: PermissionInfo::new(&[
+ permissions: get_permission_info_from_permissions(&[
Permission::MerchantConnectorAccountRead,
Permission::MerchantConnectorAccountWrite,
]),
@@ -107,7 +110,7 @@ impl ModuleInfo {
PermissionModule::Routing => Self {
module: module_name,
description,
- permissions: PermissionInfo::new(&[
+ permissions: get_permission_info_from_permissions(&[
Permission::RoutingRead,
Permission::RoutingWrite,
]),
@@ -115,12 +118,12 @@ impl ModuleInfo {
PermissionModule::Analytics => Self {
module: module_name,
description,
- permissions: PermissionInfo::new(&[Permission::Analytics]),
+ permissions: get_permission_info_from_permissions(&[Permission::Analytics]),
},
PermissionModule::Mandates => Self {
module: module_name,
description,
- permissions: PermissionInfo::new(&[
+ permissions: get_permission_info_from_permissions(&[
Permission::MandateRead,
Permission::MandateWrite,
]),
@@ -128,7 +131,7 @@ impl ModuleInfo {
PermissionModule::Customer => Self {
module: module_name,
description,
- permissions: PermissionInfo::new(&[
+ permissions: get_permission_info_from_permissions(&[
Permission::CustomerRead,
Permission::CustomerWrite,
]),
@@ -136,7 +139,7 @@ impl ModuleInfo {
PermissionModule::Disputes => Self {
module: module_name,
description,
- permissions: PermissionInfo::new(&[
+ permissions: get_permission_info_from_permissions(&[
Permission::DisputeRead,
Permission::DisputeWrite,
]),
@@ -144,7 +147,7 @@ impl ModuleInfo {
PermissionModule::ThreeDsDecisionManager => Self {
module: module_name,
description,
- permissions: PermissionInfo::new(&[
+ permissions: get_permission_info_from_permissions(&[
Permission::ThreeDsDecisionManagerRead,
Permission::ThreeDsDecisionManagerWrite,
]),
@@ -153,7 +156,7 @@ impl ModuleInfo {
PermissionModule::SurchargeDecisionManager => Self {
module: module_name,
description,
- permissions: PermissionInfo::new(&[
+ permissions: get_permission_info_from_permissions(&[
Permission::SurchargeDecisionManagerRead,
Permission::SurchargeDecisionManagerWrite,
]),
@@ -161,8 +164,46 @@ impl ModuleInfo {
PermissionModule::AccountCreate => Self {
module: module_name,
description,
- permissions: PermissionInfo::new(&[Permission::MerchantAccountCreate]),
+ permissions: get_permission_info_from_permissions(&[
+ Permission::MerchantAccountCreate,
+ ]),
},
}
}
}
+
+fn get_group_info_from_permission_group(group: PermissionGroup) -> GroupInfo {
+ let description = get_group_description(group);
+ GroupInfo {
+ group,
+ description,
+ permissions: get_permission_info_from_permissions(get_permissions_vec(&group)),
+ }
+}
+
+fn get_group_description(group: PermissionGroup) -> &'static str {
+ match group {
+ PermissionGroup::OperationsView => {
+ "View Payments, Refunds, Mandates, Disputes and Customers"
+ }
+ PermissionGroup::OperationsManage => {
+ "Create,modify and delete Payments, Refunds, Mandates, Disputes and Customers"
+ }
+ PermissionGroup::ConnectorsView => {
+ "View connected Payment Processors, Payout Processors and Fraud & Risk Manager details"
+ }
+ PermissionGroup::ConnectorsManage => "Create, modify and delete connectors like Payment Processors, Payout Processors and Fraud & Risk Manager",
+ PermissionGroup::WorkflowsView => {
+ "View Routing, 3DS Decision Manager, Surcharge Decision Manager"
+ }
+ PermissionGroup::WorkflowsManage => {
+ "Create, modify and delete Routing, 3DS Decision Manager, Surcharge Decision Manager"
+ }
+ PermissionGroup::AnalyticsView => "View Analytics",
+ PermissionGroup::UsersView => "View Users",
+ PermissionGroup::UsersManage => "Manage and invite Users to the Team",
+ PermissionGroup::MerchantDetailsView => "View Merchant Details",
+ PermissionGroup::MerchantDetailsManage => "Create, modify and delete Merchant Details like api keys, webhooks, etc",
+ PermissionGroup::OrganizationManage => "Manage organization level tasks like create new Merchant accounts, Organization level roles, etc",
+ }
+}
diff --git a/crates/router/src/services/authorization/roles.rs b/crates/router/src/services/authorization/roles.rs
index 6372799f98c..f99892c565d 100644
--- a/crates/router/src/services/authorization/roles.rs
+++ b/crates/router/src/services/authorization/roles.rs
@@ -65,22 +65,22 @@ impl RoleInfo {
.iter()
.any(|group| get_permissions_vec(group).contains(required_permission))
}
-}
-pub async fn get_role_info_from_role_id(
- state: &AppState,
- role_id: &str,
- merchant_id: &str,
- org_id: &str,
-) -> CustomResult<RoleInfo, errors::StorageError> {
- if let Some(role) = predefined_roles::PREDEFINED_ROLES.get(role_id) {
- Ok(role.clone())
- } else {
- state
- .store
- .find_role_by_role_id_in_merchant_scope(role_id, merchant_id, org_id)
- .await
- .map(RoleInfo::from)
+ pub async fn from_role_id(
+ state: &AppState,
+ role_id: &str,
+ merchant_id: &str,
+ org_id: &str,
+ ) -> CustomResult<Self, errors::StorageError> {
+ if let Some(role) = predefined_roles::PREDEFINED_ROLES.get(role_id) {
+ Ok(role.clone())
+ } else {
+ state
+ .store
+ .find_role_by_role_id_in_merchant_scope(role_id, merchant_id, org_id)
+ .await
+ .map(Self::from)
+ }
}
}
diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs
index a759bf00806..d6e878456e8 100644
--- a/crates/router/src/types/domain/user.rs
+++ b/crates/router/src/types/domain/user.rs
@@ -811,15 +811,6 @@ impl From<info::PermissionModule> for user_role_api::PermissionModule {
}
}
-impl From<info::PermissionInfo> for user_role_api::PermissionInfo {
- fn from(value: info::PermissionInfo) -> Self {
- Self {
- enum_name: value.enum_name.into(),
- description: value.description,
- }
- }
-}
-
pub enum SignInWithRoleStrategyType {
SingleRole(SignInWithSingleRoleStrategy),
MultipleRoles(SignInWithMultipleRolesStrategy),
diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs
index e9b7143a26e..c3b795d1a57 100644
--- a/crates/router/src/utils/user.rs
+++ b/crates/router/src/utils/user.rs
@@ -64,7 +64,7 @@ impl UserFromToken {
}
pub async fn get_role_info_from_db(&self, state: &AppState) -> UserResult<RoleInfo> {
- roles::get_role_info_from_role_id(state, &self.role_id, &self.merchant_id, &self.org_id)
+ roles::RoleInfo::from_role_id(state, &self.role_id, &self.merchant_id, &self.org_id)
.await
.change_context(UserErrors::InternalServerError)
}
|
2024-02-27T07:21:21Z
|
## 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 -->
Change `list_roles`, `get_role` and `get_authorization_info` api to respond with groups if asked.
### 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 #3836
## 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 following APIs have a query param called groups, setting it to true will return the following response.
1. Get role list
```
curl --location 'http://localhost:8080/user/role/list?groups=true' \
--header 'Authorization: Bearer JWT'
```
Response
```
[
{
"role_id": "merchant_iam_admin",
"groups": [
"operations_view",
"analytics_view",
"users_view",
"users_manage",
"merchant_details_view"
],
"role_name": "IAM",
"role_scope": "organization"
},
{
"role_id": "merchant_customer_support",
"groups": [
"operations_view",
"analytics_view",
"users_view",
"merchant_details_view"
],
"role_name": "Customer Support",
"role_scope": "organization"
},
{
"role_id": "merchant_admin",
"groups": [
"operations_view",
"operations_manage",
"connectors_view",
"connectors_manage",
"workflows_view",
"workflows_manage",
"analytics_view",
"users_view",
"users_manage",
"merchant_details_view",
"merchant_details_manage"
],
"role_name": "Admin",
"role_scope": "organization"
},
{
"role_id": "merchant_developer",
"groups": [
"operations_view",
"connectors_view",
"analytics_view",
"users_view",
"merchant_details_view",
"merchant_details_manage"
],
"role_name": "Developer",
"role_scope": "organization"
},
{
"role_id": "merchant_view_only",
"groups": [
"operations_view",
"connectors_view",
"workflows_view",
"analytics_view",
"users_view",
"merchant_details_view"
],
"role_name": "View Only",
"role_scope": "organization"
},
{
"role_id": "merchant_operator",
"groups": [
"operations_view",
"operations_manage",
"connectors_view",
"workflows_view",
"analytics_view",
"users_view",
"merchant_details_view"
],
"role_name": "Operator",
"role_scope": "organization"
},
{
"role_id": "role_01JlOAdLoUqtynjUfEV4",
"groups": [
"users_view"
],
"role_name": "custom_role",
"role_scope": "merchant"
}
]
```
2. Get role info
```
curl --location 'http://localhost:8080/user/role/role_01JlOAdLoUqtynjUfEV4?groups=true' \
--header 'Authorization: Bearer JWT'
```
Response
```
{
"role_id": "role_01JlOAdLoUqtynjUfEV4",
"groups": [
"users_view"
],
"role_name": "custom_role",
"role_scope": "merchant"
}
```
3. Permission Info
```
curl --location 'http://localhost:8080/user/permission_info?groups=true' \
--header 'Authorization: Bearer JWT'
```
Response
```
[
{
"group": "operations_view",
"description": "View Payments, Refunds, Mandates, Disputes and Customers",
"permissions": [
{
"enum_name": "PaymentRead",
"description": "View all payments"
},
{
"enum_name": "RefundRead",
"description": "View all refunds"
},
{
"enum_name": "MandateRead",
"description": "View mandates"
},
{
"enum_name": "DisputeRead",
"description": "View disputes"
},
{
"enum_name": "CustomerRead",
"description": "View customers"
},
{
"enum_name": "MerchantAccountRead",
"description": "View merchant account details"
}
]
},
{
"group": "operations_manage",
"description": "Create,modify and delete Payments, Refunds, Mandates, Disputes and Customers",
"permissions": [
{
"enum_name": "PaymentWrite",
"description": "Create payment, download payments data"
},
{
"enum_name": "RefundWrite",
"description": "Create refund, download refunds data"
},
{
"enum_name": "MandateWrite",
"description": "Create and update mandates"
},
{
"enum_name": "DisputeWrite",
"description": "Create and update disputes"
},
{
"enum_name": "CustomerWrite",
"description": "Create, update and delete customers"
},
{
"enum_name": "MerchantAccountRead",
"description": "View merchant account details"
}
]
},
{
"group": "connectors_view",
"description": "View connected Payment Processors, Payout Processors and Fraud & Risk Manager details",
"permissions": [
{
"enum_name": "MerchantConnectorAccountRead",
"description": "View connectors configured"
},
{
"enum_name": "MerchantAccountRead",
"description": "View merchant account details"
}
]
},
{
"group": "connectors_manage",
"description": "Create, modify and delete connectors like Payment Processors, Payout Processors and Fraud & Risk Manager",
"permissions": [
{
"enum_name": "MerchantConnectorAccountWrite",
"description": "Create, update, verify and delete connector configurations"
},
{
"enum_name": "MerchantAccountRead",
"description": "View merchant account details"
}
]
},
{
"group": "workflows_view",
"description": "View Routing, 3DS Decision Manager, Surcharge Decision Manager",
"permissions": [
{
"enum_name": "RoutingRead",
"description": "View routing configuration"
},
{
"enum_name": "ThreeDsDecisionManagerRead",
"description": "View all 3DS decision rules configured for a merchant"
},
{
"enum_name": "SurchargeDecisionManagerRead",
"description": "View all the surcharge decision rules"
},
{
"enum_name": "MerchantConnectorAccountRead",
"description": "View connectors configured"
},
{
"enum_name": "MerchantAccountRead",
"description": "View merchant account details"
}
]
},
{
"group": "workflows_manage",
"description": "Create, modify and delete Routing, 3DS Decision Manager, Surcharge Decision Manager",
"permissions": [
{
"enum_name": "RoutingWrite",
"description": "Create and activate routing configurations"
},
{
"enum_name": "ThreeDsDecisionManagerWrite",
"description": "Create and update 3DS decision rules"
},
{
"enum_name": "SurchargeDecisionManagerWrite",
"description": "Create and update the surcharge decision rules"
},
{
"enum_name": "MerchantConnectorAccountRead",
"description": "View connectors configured"
},
{
"enum_name": "MerchantAccountRead",
"description": "View merchant account details"
}
]
},
{
"group": "analytics_view",
"description": "View Analytics",
"permissions": [
{
"enum_name": "Analytics",
"description": "Access to analytics module"
},
{
"enum_name": "MerchantAccountRead",
"description": "View merchant account details"
}
]
},
{
"group": "users_view",
"description": "View Users",
"permissions": [
{
"enum_name": "UsersRead",
"description": "View all the users for a merchant"
},
{
"enum_name": "MerchantAccountRead",
"description": "View merchant account details"
}
]
},
{
"group": "users_manage",
"description": "Manage and invite Users to the Team",
"permissions": [
{
"enum_name": "UsersWrite",
"description": "Invite users, assign and update roles"
},
{
"enum_name": "MerchantAccountRead",
"description": "View merchant account details"
}
]
},
{
"group": "merchant_details_view",
"description": "View Merchant Details",
"permissions": [
{
"enum_name": "MerchantAccountRead",
"description": "View merchant account details"
}
]
},
{
"group": "merchant_details_manage",
"description": "Create, modify and delete Merchant Details like api keys, webhooks, etc",
"permissions": [
{
"enum_name": "MerchantAccountWrite",
"description": "Update merchant account details, configure webhooks, manage api keys"
},
{
"enum_name": "ApiKeyRead",
"description": "View API keys (masked generated for the system"
},
{
"enum_name": "ApiKeyWrite",
"description": "Create and update API keys"
},
{
"enum_name": "MerchantAccountRead",
"description": "View merchant account details"
}
]
},
{
"group": "organization_manage",
"description": "Manage organization level tasks like create new Merchant accounts, Organization level roles, etc",
"permissions": [
{
"enum_name": "MerchantAccountCreate",
"description": "Create merchant account"
},
{
"enum_name": "MerchantAccountRead",
"description": "View merchant account details"
}
]
}
]
```
## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
1c6913be747bd3da53fa2b48e339810bb30226e7
|
|
juspay/hyperswitch
|
juspay__hyperswitch-3818
|
Bug: [FEATURE] : [Fiserv] mask pii information in connector request and response
### Feature Description
Mask pii information passed and received in the connector request and response
### Possible Implementation
Refactor all sensitive response and request fields secret
### 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/fiserv/transformers.rs b/crates/router/src/connector/fiserv/transformers.rs
index e2511dc8d56..b8dd3c9643f 100644
--- a/crates/router/src/connector/fiserv/transformers.rs
+++ b/crates/router/src/connector/fiserv/transformers.rs
@@ -62,8 +62,8 @@ pub enum Source {
},
#[allow(dead_code)]
GooglePay {
- data: String,
- signature: String,
+ data: Secret<String>,
+ signature: Secret<String>,
version: String,
},
}
@@ -80,8 +80,8 @@ pub struct CardData {
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GooglePayToken {
- signature: String,
- signed_message: String,
+ signature: Secret<String>,
+ signed_message: Secret<String>,
protocol_version: String,
}
@@ -104,7 +104,7 @@ pub struct TransactionDetails {
#[serde(rename_all = "camelCase")]
pub struct MerchantDetails {
merchant_id: Secret<String>,
- terminal_id: Option<String>,
+ terminal_id: Option<Secret<String>>,
}
#[derive(Default, Debug, Serialize)]
@@ -428,7 +428,7 @@ pub struct ReferenceTransactionDetails {
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct FiservSessionObject {
- pub terminal_id: String,
+ pub terminal_id: Secret<String>,
}
impl TryFrom<&Option<pii::SecretSerdeValue>> for FiservSessionObject {
|
2024-02-26T09:58:16Z
|
## 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 -->
Mask pii information passed and received in the connector request and response for Fiserv.
## Test case
1. Create a card payment with fiserv
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key:{{api_key}}' \
--data-raw '{
"amount": 2000,
"currency": "USD",
"confirm": true,
"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": "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"
}
},
"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"
},
"payment_method": "card",
"payment_method_data": {
"card": {
"card_number": "4111111111111111",
"card_exp_month": "10",
"card_exp_year": "30",
"card_holder_name": "Joseph Doe",
"card_cvc": "123"
}
}
}'
```
1.b. Check if all the sensitive data in the `masked_response` and also in `request` is masked
```
curl --location '{{base_url}}/analytics/v1/connector_event_logs?type=Payment&payment_id={{payment_id}}' \
--header 'sec-ch-ua: "Not A(Brand";v="99", "Google Chrome";v="121", "Chromium";v="121"' \
--header 'sec-ch-ua-mobile: ?0' \
--header 'authorization: Bearer JWT_token' \
--header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36' \
--header 'Content-Type: application/json' \
--header 'Referer: https://integ.hyperswitch.io/' \
--header 'api-key: {{api-key}}' \
--header 'sec-ch-ua-platform: "macOS"'
```
Masked Request
```
request\":\"{\\\"amount\\\":{\\\"total\\\":20.0,\\\"currency\\\":\\\"USD\\\"},\\\"source\\\":{\\\"sourceType\\\":\\\"PaymentCard\\\",\\\"card\\\":{\\\"cardData\\\":\\\"411111**********\\\",\\\"expirationMonth\\\":\\\"*** alloc::string::String ***\\\",\\\"expirationYear\\\":\\\"*** alloc::string::String ***\\\",\\\"securityCode\\\":\\\"*** alloc::string::String ***\\\"}},\\\"transactionDetails\\\":{\\\"captureFlag\\\":true,\\\"reversalReasonCode\\\":null,\\\"merchantTransactionId\\\":\\\"pay_IRGqmgQ7FkrCPXxyCWfa_1\\\"},\\\"merchantDetails\\\":{\\\"merchantId\\\":\\\"*** alloc::string::String ***\\\",\\\"terminalId\\\":\\\"*** alloc::string::String ***\\\"},\\\"transactionInteraction\\\":{\\\"origin\\\":\\\"ECOM\\\",\\\"eciIndicator\\\":\\\"CHANNEL_ENCRYPTED\\\",\\\"posConditionCode\\\":\\\"CARD_NOT_PRESENT_ECOM\\\"}}
```
Masked Response
```
"masked_response\":\"{\\\"gatewayResponse\\\":{\\\"gatewayTransactionId\\\":null,\\\"transactionState\\\":\\\"CAPTURED\\\",\\\"transactionProcessingDetails\\\":{\\\"orderId\\\":\\\"CHG01a86281900c326c5f580655313a9cc7cb\\\",\\\"transactionId\\\":\\\"4a695b8bd77b448d80ebb13640561fe7\\\"}}}
```
## Impacted Area
> Payment Create flow
## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
75c633fc7c37341177597041ccbcdfc3cf9e236f
|
|
juspay/hyperswitch
|
juspay__hyperswitch-3816
|
Bug: [Analytics] - Add error_reason field in clickhouse column
|
diff --git a/crates/analytics/docs/clickhouse/cluster_setup/scripts/dispute_analytics.sql b/crates/analytics/docs/clickhouse/cluster_setup/scripts/dispute_analytics.sql
deleted file mode 100644
index 92a748ff489..00000000000
--- a/crates/analytics/docs/clickhouse/cluster_setup/scripts/dispute_analytics.sql
+++ /dev/null
@@ -1,142 +0,0 @@
-CREATE TABLE hyperswitch.dispute_queue on cluster '{cluster}' (
- `dispute_id` String,
- `amount` String,
- `currency` String,
- `dispute_stage` LowCardinality(String),
- `dispute_status` LowCardinality(String),
- `payment_id` String,
- `attempt_id` String,
- `merchant_id` String,
- `connector_status` String,
- `connector_dispute_id` String,
- `connector_reason` Nullable(String),
- `connector_reason_code` Nullable(String),
- `challenge_required_by` Nullable(DateTime) CODEC(T64, LZ4),
- `connector_created_at` Nullable(DateTime) CODEC(T64, LZ4),
- `connector_updated_at` Nullable(DateTime) CODEC(T64, LZ4),
- `created_at` DateTime CODEC(T64, LZ4),
- `modified_at` DateTime CODEC(T64, LZ4),
- `connector` LowCardinality(String),
- `evidence` Nullable(String),
- `profile_id` Nullable(String),
- `merchant_connector_id` Nullable(String),
- `sign_flag` Int8
-) ENGINE = Kafka SETTINGS kafka_broker_list = 'kafka0:29092',
-kafka_topic_list = 'hyperswitch-dispute-events',
-kafka_group_name = 'hyper-c1',
-kafka_format = 'JSONEachRow',
-kafka_handle_error_mode = 'stream';
-
-
-CREATE MATERIALIZED VIEW hyperswitch.dispute_mv on cluster '{cluster}' TO hyperswitch.dispute (
- `dispute_id` String,
- `amount` String,
- `currency` String,
- `dispute_stage` LowCardinality(String),
- `dispute_status` LowCardinality(String),
- `payment_id` String,
- `attempt_id` String,
- `merchant_id` String,
- `connector_status` String,
- `connector_dispute_id` String,
- `connector_reason` Nullable(String),
- `connector_reason_code` Nullable(String),
- `challenge_required_by` Nullable(DateTime64(3)),
- `connector_created_at` Nullable(DateTime64(3)),
- `connector_updated_at` Nullable(DateTime64(3)),
- `created_at` DateTime64(3),
- `modified_at` DateTime64(3),
- `connector` LowCardinality(String),
- `evidence` Nullable(String),
- `profile_id` Nullable(String),
- `merchant_connector_id` Nullable(String),
- `inserted_at` DateTime64(3),
- `sign_flag` Int8
-) AS
-SELECT
- dispute_id,
- amount,
- currency,
- dispute_stage,
- dispute_status,
- payment_id,
- attempt_id,
- merchant_id,
- connector_status,
- connector_dispute_id,
- connector_reason,
- connector_reason_code,
- challenge_required_by,
- connector_created_at,
- connector_updated_at,
- created_at,
- modified_at,
- connector,
- evidence,
- profile_id,
- merchant_connector_id,
- now() as inserted_at,
- sign_flag
-FROM
- hyperswitch.dispute_queue
-WHERE length(_error) = 0;
-
-
-CREATE TABLE hyperswitch.dispute_clustered on cluster '{cluster}' (
- `dispute_id` String,
- `amount` String,
- `currency` String,
- `dispute_stage` LowCardinality(String),
- `dispute_status` LowCardinality(String),
- `payment_id` String,
- `attempt_id` String,
- `merchant_id` String,
- `connector_status` String,
- `connector_dispute_id` String,
- `connector_reason` Nullable(String),
- `connector_reason_code` Nullable(String),
- `challenge_required_by` Nullable(DateTime) CODEC(T64, LZ4),
- `connector_created_at` Nullable(DateTime) CODEC(T64, LZ4),
- `connector_updated_at` Nullable(DateTime) CODEC(T64, LZ4),
- `created_at` DateTime DEFAULT now() CODEC(T64, LZ4),
- `modified_at` DateTime DEFAULT now() CODEC(T64, LZ4),
- `connector` LowCardinality(String),
- `evidence` String DEFAULT '{}' CODEC(T64, LZ4),
- `profile_id` Nullable(String),
- `merchant_connector_id` Nullable(String),
- `inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4),
- `sign_flag` Int8
- INDEX connectorIndex connector TYPE bloom_filter GRANULARITY 1,
- INDEX disputeStatusIndex dispute_status TYPE bloom_filter GRANULARITY 1,
- INDEX disputeStageIndex dispute_stage TYPE bloom_filter GRANULARITY 1
-) ENGINE = ReplicatedCollapsingMergeTree(
- '/clickhouse/{installation}/{cluster}/tables/{shard}/hyperswitch/dispute_clustered',
- '{replica}',
- dispute_status
-)
-PARTITION BY toStartOfDay(created_at)
-ORDER BY
- (created_at, merchant_id, dispute_id)
-TTL created_at + toIntervalMonth(6);
-
-
-CREATE MATERIALIZED VIEW hyperswitch.dispute_parse_errors on cluster '{cluster}'
-(
- `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 hyperswitch.dispute_queue
-WHERE length(_error) > 0
-;
\ No newline at end of file
diff --git a/crates/analytics/docs/clickhouse/scripts/api_events.sql b/crates/analytics/docs/clickhouse/scripts/api_events.sql
index 49a6472eaa4..e466fc56cb6 100644
--- a/crates/analytics/docs/clickhouse/scripts/api_events.sql
+++ b/crates/analytics/docs/clickhouse/scripts/api_events.sql
@@ -58,7 +58,7 @@ CREATE TABLE api_events_dist (
`hs_latency` Nullable(UInt128),
`http_method` LowCardinality(String),
`url_path` String,
- `dispute_id` Nullable(String)
+ `dispute_id` Nullable(String),
INDEX flowIndex flow_type TYPE bloom_filter GRANULARITY 1,
INDEX apiIndex api_flow TYPE bloom_filter GRANULARITY 1,
INDEX statusIndex status_code TYPE bloom_filter GRANULARITY 1
diff --git a/crates/analytics/docs/clickhouse/scripts/payment_attempts.sql b/crates/analytics/docs/clickhouse/scripts/payment_attempts.sql
index 276e311e57a..8b7715044c1 100644
--- a/crates/analytics/docs/clickhouse/scripts/payment_attempts.sql
+++ b/crates/analytics/docs/clickhouse/scripts/payment_attempts.sql
@@ -29,6 +29,15 @@ CREATE TABLE payment_attempts_queue (
`created_at` DateTime CODEC(T64, LZ4),
`last_synced` Nullable(DateTime) CODEC(T64, LZ4),
`modified_at` DateTime CODEC(T64, LZ4),
+ `payment_method_data` Nullable(String),
+ `error_reason` Nullable(String),
+ `multiple_capture_count` Nullable(Int16),
+ `amount_capturable` Nullable(UInt64) ,
+ `merchant_connector_id` Nullable(String),
+ `net_amount` Nullable(UInt64) ,
+ `unified_code` Nullable(String),
+ `unified_message` Nullable(String),
+ `mandate_data` Nullable(String),
`sign_flag` Int8
) ENGINE = Kafka SETTINGS kafka_broker_list = 'kafka0:29092',
kafka_topic_list = 'hyperswitch-payment-attempt-events',
@@ -67,6 +76,15 @@ CREATE TABLE payment_attempt_dist (
`created_at` DateTime DEFAULT now() CODEC(T64, LZ4),
`last_synced` Nullable(DateTime) CODEC(T64, LZ4),
`modified_at` DateTime DEFAULT now() CODEC(T64, LZ4),
+ `payment_method_data` Nullable(String),
+ `error_reason` Nullable(String),
+ `multiple_capture_count` Nullable(Int16),
+ `amount_capturable` Nullable(UInt64) ,
+ `merchant_connector_id` Nullable(String),
+ `net_amount` Nullable(UInt64) ,
+ `unified_code` Nullable(String),
+ `unified_message` Nullable(String),
+ `mandate_data` Nullable(String),
`inserted_at` DateTime DEFAULT now() CODEC(T64, LZ4),
`sign_flag` Int8,
INDEX connectorIndex connector TYPE bloom_filter GRANULARITY 1,
@@ -115,6 +133,15 @@ CREATE MATERIALIZED VIEW kafka_parse_pa TO payment_attempt_dist (
`capture_on` Nullable(DateTime64(3)),
`last_synced` Nullable(DateTime64(3)),
`modified_at` DateTime64(3),
+ `payment_method_data` Nullable(String),
+ `error_reason` Nullable(String),
+ `multiple_capture_count` Nullable(Int16),
+ `amount_capturable` Nullable(UInt64) ,
+ `merchant_connector_id` Nullable(String),
+ `net_amount` Nullable(UInt64) ,
+ `unified_code` Nullable(String),
+ `unified_message` Nullable(String),
+ `mandate_data` Nullable(String),
`inserted_at` DateTime64(3),
`sign_flag` Int8
) AS
@@ -149,6 +176,15 @@ SELECT
capture_on,
last_synced,
modified_at,
+ payment_method_data,
+ error_reason,
+ multiple_capture_count,
+ amount_capturable,
+ merchant_connector_id,
+ net_amount,
+ unified_code,
+ unified_message,
+ mandate_data,
now() as inserted_at,
sign_flag
FROM
diff --git a/crates/router/src/services/kafka/payment_attempt.rs b/crates/router/src/services/kafka/payment_attempt.rs
index ea0721f418e..98f88fb69f5 100644
--- a/crates/router/src/services/kafka/payment_attempt.rs
+++ b/crates/router/src/services/kafka/payment_attempt.rs
@@ -1,4 +1,5 @@
-use data_models::payments::payment_attempt::PaymentAttempt;
+// use diesel_models::enums::MandateDetails;
+use data_models::{mandates::MandateDetails, payments::payment_attempt::PaymentAttempt};
use diesel_models::enums as storage_enums;
use time::OffsetDateTime;
@@ -39,6 +40,15 @@ pub struct KafkaPaymentAttempt<'a> {
// 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: i64,
+ pub merchant_connector_id: Option<&'a String>,
+ pub net_amount: i64,
+ pub unified_code: Option<&'a String>,
+ pub unified_message: Option<&'a String>,
+ pub mandate_data: Option<&'a MandateDetails>,
}
impl<'a> KafkaPaymentAttempt<'a> {
@@ -74,6 +84,15 @@ impl<'a> KafkaPaymentAttempt<'a> {
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(),
}
}
}
|
2024-02-26T07:09:51Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [x] Enhancement
- [ ] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [ ] CI/CD
## Description
<!-- Adding new fields in Kafka struct for analytics usecase -->
This PR adds more fields which we would want to send to Kafka for various usecases of search and analytics from attempts table in PSQL
Fields which have been added are
```
payment_method_data,
error_reason,
multiple_capture_count,
amount_capturable,
merchant_connector_id,
net_amount,
unified_code,
unified_message,
mandate_data,
```
### 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)?
-->
Curl
```curl
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: key' \
--data-raw '{
"amount": 60,
"currency": "USD",
"confirm": true,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
"amount_to_capture": 60,
"customer_id": "SHIVANSH",
"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": "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"
}
}'
```

Tested it locally , by creating payments and observing what events are being generated for that payment which is being pushed to Kafka
Can test the changes in loki though once deployed
As soon as we deploy this
The fields which we have
We’ll get those fields under `topic="hyperswitch-payment-attempt-events"`
## 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
|
f4d0e2b441a25048186be4b9d0871e2473a6f357
|
|
juspay/hyperswitch
|
juspay__hyperswitch-3801
|
Bug: [REFACTOR] provide an identifier for the api key in the expiry reminder email
### Issue Description:
Currently, our system sends out reminder emails to merchants when their API key is about to expire. However, since merchants can create multiple API keys, the email lacks clarity on which specific API key is expiring.
### Proposed Solution:
Refactor the api key expiry reminder workflow to include the name and prefix of the expiring API key in email. This will help merchants easily identify which API key requires attention without confusion.
### Details:
Update the email template to include the following information:
API Key Name along with Prefix in below format -
`API_KEY_NAME [PREFIX]`
### Reference:
Check `ApiKeyExpiryTrackingData` type in https://github.com/juspay/hyperswitch/blob/2c95dcd19778726f476b219271dc42da182088af/crates/diesel_models/src/api_keys.rs
|
diff --git a/crates/diesel_models/src/api_keys.rs b/crates/diesel_models/src/api_keys.rs
index 1875fc4dc51..7676e20d224 100644
--- a/crates/diesel_models/src/api_keys.rs
+++ b/crates/diesel_models/src/api_keys.rs
@@ -141,6 +141,8 @@ mod diesel_impl {
pub struct ApiKeyExpiryTrackingData {
pub key_id: String,
pub merchant_id: String,
+ pub api_key_name: String,
+ pub prefix: String,
pub api_key_expiry: Option<PrimitiveDateTime>,
// Days on which email reminder about api_key expiry has to be sent, prior to it's expiry.
pub expiry_reminder_days: Vec<u8>,
diff --git a/crates/router/src/core/api_keys.rs b/crates/router/src/core/api_keys.rs
index 7d2069618d5..a2fcacb3b3d 100644
--- a/crates/router/src/core/api_keys.rs
+++ b/crates/router/src/core/api_keys.rs
@@ -207,6 +207,8 @@ pub async fn add_api_key_expiry_task(
let api_key_expiry_tracker = storage::ApiKeyExpiryTrackingData {
key_id: api_key.key_id.clone(),
merchant_id: api_key.merchant_id.clone(),
+ api_key_name: api_key.name.clone(),
+ prefix: api_key.prefix.clone(),
// We need API key expiry too, because we need to decide on the schedule_time in
// execute_workflow() where we won't be having access to the Api key object.
api_key_expiry: api_key.expires_at,
@@ -369,6 +371,8 @@ pub async fn update_api_key_expiry_task(
let updated_tracking_data = &storage::ApiKeyExpiryTrackingData {
key_id: api_key.key_id.clone(),
merchant_id: api_key.merchant_id.clone(),
+ api_key_name: api_key.name.clone(),
+ prefix: api_key.prefix.clone(),
api_key_expiry: api_key.expires_at,
expiry_reminder_days,
};
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 1865ae38141..772602d71e7 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
@@ -43,20 +43,7 @@
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"
@@ -96,13 +83,13 @@
line-height: 36px;
margin: 0 auto;
padding: 0;
- text-align: center;
+ 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 will expire in {expires_in} days. To ensure uninterrupted
+ 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>
@@ -118,39 +105,11 @@
margin: 0 auto;
padding: 0;
"
- width="100%"
- ></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
- 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"
@@ -162,7 +121,7 @@
line-height: 36px;
margin: 0 auto;
padding: 0;
- text-align: center;
+ text-align: left;
"
align="center"
>
@@ -184,20 +143,7 @@
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>
diff --git a/crates/router/src/services/email/types.rs b/crates/router/src/services/email/types.rs
index fa1eecbaab8..2fbe7d606e5 100644
--- a/crates/router/src/services/email/types.rs
+++ b/crates/router/src/services/email/types.rs
@@ -50,6 +50,8 @@ pub enum EmailBody {
},
ApiKeyExpiryReminder {
expires_in: u8,
+ api_key_name: String,
+ prefix: String,
},
}
@@ -128,8 +130,14 @@ Email : {user_email}
(note: This is an auto generated email. Use merchant email for any further communications)",
),
- EmailBody::ApiKeyExpiryReminder { expires_in } => format!(
+ EmailBody::ApiKeyExpiryReminder {
+ expires_in,
+ api_key_name,
+ prefix,
+ } => format!(
include_str!("assets/api_key_expiry_reminder.html"),
+ api_key_name = api_key_name,
+ prefix = prefix,
expires_in = expires_in,
),
}
@@ -441,6 +449,8 @@ pub struct ApiKeyExpiryReminder {
pub recipient_email: domain::UserEmail,
pub subject: &'static str,
pub expires_in: u8,
+ pub api_key_name: String,
+ pub prefix: String,
}
#[async_trait::async_trait]
@@ -450,6 +460,8 @@ impl EmailData for ApiKeyExpiryReminder {
let body = html::get_html_body(EmailBody::ApiKeyExpiryReminder {
expires_in: self.expires_in,
+ api_key_name: self.api_key_name.clone(),
+ prefix: self.prefix.clone(),
});
Ok(EmailContents {
diff --git a/crates/router/src/workflows/api_key_expiry.rs b/crates/router/src/workflows/api_key_expiry.rs
index e9e1f323708..c5914810108 100644
--- a/crates/router/src/workflows/api_key_expiry.rs
+++ b/crates/router/src/workflows/api_key_expiry.rs
@@ -54,6 +54,10 @@ impl ProcessTrackerWorkflow<AppState> for ApiKeyExpiryWorkflow {
let retry_count = process.retry_count;
+ let api_key_name = tracking_data.api_key_name.clone();
+
+ let prefix = tracking_data.prefix.clone();
+
let expires_in = tracking_data
.expiry_reminder_days
.get(
@@ -69,6 +73,9 @@ impl ProcessTrackerWorkflow<AppState> for ApiKeyExpiryWorkflow {
})?,
subject: "API Key Expiry Notice",
expires_in: *expires_in,
+ api_key_name,
+ prefix,
+
};
state
|
2024-02-29T08:09: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 -->
Refactored the api key expiry reminder workflow to include the name and prefix of the expiring API key in the email
### 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 the issue #3801
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).
-->
It fixes #3801
## 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 merchant account
2. Create an api key with expiry somewhat closer to 7 days from current time in UTC format.
3. You should get an email something like below once api key expiry is exactly 7 days from current time

## 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`
- [ ] I reviewed the submitted code
- [ ] I added unit tests for my changes where possible
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
6b078fa339b5404f7c730322bc8597cd1104ec15
|
|
juspay/hyperswitch
|
juspay__hyperswitch-3806
|
Bug: [BUG] collections fail to import if variable is not a string
Newman runner i.e., newman-dir does support dynamic values but only string variables and not other variables say integer. Hence, variables like `"{{value}}"` is the only way for you to export the collection json file to its directory structure and having the variables like `{{value}}` will result in the `dir-export` / `dir-import` commands to fail.
This bug affects collections that use dynamic values for amount fields. One such connector is NMI which has a hard limit on transactions i.e., once a payment for a n amount is done, the payment cannot be repeated up until the next 20 mins. If not, the payment is flagged as duplicate. The only work around for this is to use dynamic values. But that is restricted because of this bug with `newman-dir`.
One work around that we can do is to:
- export the collection to its json format
- remove double quotes (`\"`) for integer fields
- run the collection -- json and not dir
- and all this should happen in run time
Example:
```sh
newman dir-import -o /tmp/generated_collection.json
perl -pi -e 's/\\"{{value}}\\"/{{value}}/g' /tmp/generated_collection.json
newman run /tmp/generated_collection.json
```
We can use `sed` / `regex` instead of `perl` as well.
Reference:
https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=9a9eef47fb334cb686b2fff360e09536
https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=4e5ead4663c85da803b0a2c2030852eb
https://regex101.com/r/G6iapi/1
https://www.regular-expressions.info/named.html
|
diff --git a/Cargo.lock b/Cargo.lock
index 2c9293c1701..7823e917ed5 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4977,14 +4977,14 @@ dependencies = [
[[package]]
name = "regex"
-version = "1.9.6"
+version = "1.10.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ebee201405406dbf528b8b672104ae6d6d63e6d118cb10e4d51abbc7b58044ff"
+checksum = "b62dbe01f0b06f9d8dc7d49e05a0785f153b00b2c227856282f671e0318c9b15"
dependencies = [
"aho-corasick",
"memchr",
- "regex-automata 0.3.9",
- "regex-syntax 0.7.5",
+ "regex-automata 0.4.5",
+ "regex-syntax 0.8.2",
]
[[package]]
@@ -4998,13 +4998,13 @@ dependencies = [
[[package]]
name = "regex-automata"
-version = "0.3.9"
+version = "0.4.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "59b23e92ee4318893fa3fe3e6fb365258efbfe6ac6ab30f090cdcbb7aa37efa9"
+checksum = "5bb987efffd3c6d0d8f5f89510bb458559eab11e4f869acb20bf845e016259cd"
dependencies = [
"aho-corasick",
"memchr",
- "regex-syntax 0.7.5",
+ "regex-syntax 0.8.2",
]
[[package]]
@@ -5031,6 +5031,12 @@ version = "0.7.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dbb5fb1acd8a1a18b3dd5be62d25485eb770e05afb408a9627d14d451bae12da"
+[[package]]
+name = "regex-syntax"
+version = "0.8.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c08c74e62047bb2de4ff487b251e4a92e24f48745648451635cec7d591162d9f"
+
[[package]]
name = "rend"
version = "0.4.1"
@@ -6356,6 +6362,7 @@ dependencies = [
"clap",
"masking",
"rand 0.8.5",
+ "regex",
"reqwest",
"serde",
"serde_json",
diff --git a/crates/test_utils/Cargo.toml b/crates/test_utils/Cargo.toml
index ceb188b74db..59ff36e6cc5 100644
--- a/crates/test_utils/Cargo.toml
+++ b/crates/test_utils/Cargo.toml
@@ -17,6 +17,7 @@ async-trait = "0.1.68"
base64 = "0.21.2"
clap = { version = "4.3.2", default-features = false, features = ["std", "derive", "help", "usage"] }
rand = "0.8.5"
+regex = "1.10.3"
reqwest = { version = "0.11.18", features = ["native-tls"] }
serde = { version = "1.0.193", features = ["derive"] }
serde_json = "1.0.108"
diff --git a/crates/test_utils/src/main.rs b/crates/test_utils/src/main.rs
index 22c91e063d8..006075895b5 100644
--- a/crates/test_utils/src/main.rs
+++ b/crates/test_utils/src/main.rs
@@ -16,28 +16,20 @@ fn main() {
};
let status = child.wait();
- if runner.file_modified_flag {
- let git_status = Command::new("git")
- .args([
- "restore",
- format!("{}/event.prerequest.js", runner.collection_path).as_str(),
- ])
- .output();
+ // Filter out None values leaving behind Some(Path)
+ let paths: Vec<String> = runner.modified_file_paths.into_iter().flatten().collect();
+ let git_status = Command::new("git").arg("restore").args(&paths).output();
- match git_status {
- Ok(output) => {
- if output.status.success() {
- let stdout_str = String::from_utf8_lossy(&output.stdout);
- println!("Git command executed successfully: {stdout_str}");
- } else {
- let stderr_str = String::from_utf8_lossy(&output.stderr);
- eprintln!("Git command failed with error: {stderr_str}");
- }
- }
- Err(e) => {
- eprintln!("Error running Git: {e}");
+ match git_status {
+ Ok(output) => {
+ if !output.status.success() {
+ let stderr_str = String::from_utf8_lossy(&output.stderr);
+ eprintln!("Git command failed with error: {stderr_str}");
}
}
+ Err(e) => {
+ eprintln!("Error running Git: {e}");
+ }
}
let exit_code = match status {
diff --git a/crates/test_utils/src/newman_runner.rs b/crates/test_utils/src/newman_runner.rs
index 961853548a2..e70c630cffe 100644
--- a/crates/test_utils/src/newman_runner.rs
+++ b/crates/test_utils/src/newman_runner.rs
@@ -1,7 +1,14 @@
-use std::{env, io::Write, path::Path, process::Command};
+use std::{
+ env,
+ fs::{self, OpenOptions},
+ io::{self, Write},
+ path::Path,
+ process::{exit, Command},
+};
use clap::{arg, command, Parser};
use masking::PeekInterface;
+use regex::Regex;
use crate::connector_auth::{ConnectorAuthType, ConnectorAuthenticationMap};
#[derive(Parser)]
@@ -33,14 +40,24 @@ struct Args {
pub struct ReturnArgs {
pub newman_command: Command,
- pub file_modified_flag: bool,
+ pub modified_file_paths: Vec<Option<String>>,
pub collection_path: String,
}
-// Just by the name of the connector, this function generates the name of the collection dir
+// Generates the name of the collection JSON file for the specified connector.
+// Example: CONNECTOR_NAME="stripe" -> OUTPUT: postman/collection-json/stripe.postman_collection.json
+#[inline]
+fn get_collection_path(name: impl AsRef<str>) -> String {
+ format!(
+ "postman/collection-json/{}.postman_collection.json",
+ name.as_ref()
+ )
+}
+
+// Generates the name of the collection directory for the specified connector.
// Example: CONNECTOR_NAME="stripe" -> OUTPUT: postman/collection-dir/stripe
#[inline]
-fn get_path(name: impl AsRef<str>) -> String {
+fn get_dir_path(name: impl AsRef<str>) -> String {
format!("postman/collection-dir/{}", name.as_ref())
}
@@ -72,22 +89,34 @@ pub fn generate_newman_command() -> ReturnArgs {
let base_url = args.base_url;
let admin_api_key = args.admin_api_key;
- let collection_path = get_path(&connector_name);
+ let collection_path = get_collection_path(&connector_name);
+ let collection_dir_path = get_dir_path(&connector_name);
let auth_map = ConnectorAuthenticationMap::new();
let inner_map = auth_map.inner();
- // Newman runner
- // Depending on the conditions satisfied, variables are added. Since certificates of stripe have already
- // been added to the postman collection, those conditions are set to true and collections that have
- // variables set up for certificate, will consider those variables and will fail.
+ /*
+ Newman runner
+ Certificate keys are added through secrets in CI, so there's no need to explicitly pass it as arguments.
+ It can be overridden by explicitly passing certificates as arguments.
+
+ If the collection requires certificates (Stripe collection for example) during the merchant connector account create step,
+ then Stripe's certificates will be passed implicitly (for now).
+ If any other connector requires certificates to be passed, that has to be passed explicitly for now.
+ */
let mut newman_command = Command::new("newman");
- newman_command.args(["dir-run", &collection_path]);
+ 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}")]);
- if let Some(auth_type) = inner_map.get(&connector_name) {
+ let custom_header_exist = check_for_custom_headers(args.custom_headers, &collection_dir_path);
+
+ // validation of connector is needed here as a work around to the limitation of the fork of newman that Hyperswitch uses
+ let (connector_name, modified_collection_file_paths) =
+ check_connector_for_dynamic_amount(&connector_name);
+
+ if let Some(auth_type) = inner_map.get(connector_name) {
match auth_type {
ConnectorAuthType::HeaderKey { api_key } => {
newman_command.args([
@@ -187,24 +216,126 @@ pub fn generate_newman_command() -> ReturnArgs {
newman_command.arg("--verbose");
}
- let mut modified = false;
- if let Some(headers) = &args.custom_headers {
+ 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> {
+ if let Some(headers) = &headers {
for header in headers {
if let Some((key, value)) = header.split_once(':') {
let content_to_insert =
format!(r#"pm.request.headers.add({{key: "{key}", value: "{value}"}});"#);
- if insert_content(&collection_path, &content_to_insert).is_ok() {
- modified = true;
+
+ if let Err(err) = insert_content(path, &content_to_insert) {
+ eprintln!("An error occurred while inserting the custom header: {err}");
}
} else {
eprintln!("Invalid header format: {}", header);
}
}
+
+ return Some(format!("{}/event.prerequest.js", path));
}
+ None
+}
- ReturnArgs {
- newman_command,
- file_modified_flag: modified,
- collection_path,
+// If the connector name exists in dynamic_amount_connectors,
+// the corresponding collection is modified at runtime to remove double quotes
+pub fn check_connector_for_dynamic_amount(connector_name: &str) -> (&str, Option<String>) {
+ let collection_dir_path = get_dir_path(connector_name);
+
+ let dynamic_amount_connectors = ["nmi", "powertranz"];
+
+ if dynamic_amount_connectors.contains(&connector_name) {
+ return remove_quotes_for_integer_values(connector_name).unwrap_or((connector_name, None));
+ }
+ /*
+ If connector name does not exist in dynamic_amount_connectors but we want to run it with custom headers,
+ since we're running from collections directly, we'll have to export the collection again and it is much simpler.
+ We could directly inject the custom-headers using regex, but it is not encouraged as it is hard
+ to determine the place of edit.
+ */
+ export_collection(connector_name, collection_dir_path);
+
+ (connector_name, None)
+}
+
+/*
+Existing issue with the fork of newman is that, it requires you to pass variables like `{{value}}` within
+double quotes without which it fails to execute.
+For integer values like `amount`, this is a bummer as it flags the value stating it is of type
+string and not integer.
+Refactoring is done in 2 steps:
+- Export the collection to json (although the json will be up-to-date, we export it again for safety)
+- Use regex to replace the values which removes double quotes from integer values
+ Ex: \"{{amount}}\" -> {{amount}}
+*/
+
+pub fn remove_quotes_for_integer_values(
+ connector_name: &str,
+) -> Result<(&str, Option<String>), io::Error> {
+ let collection_path = get_collection_path(connector_name);
+ let collection_dir_path = get_dir_path(connector_name);
+
+ let values_to_replace = [
+ "amount",
+ "another_random_number",
+ "capture_amount",
+ "random_number",
+ "refund_amount",
+ ];
+
+ export_collection(connector_name, collection_dir_path);
+
+ let mut contents = fs::read_to_string(&collection_path)?;
+ for value_to_replace in values_to_replace {
+ if let Ok(re) = Regex::new(&format!(
+ r#"\\"(?P<field>\{{\{{{}\}}\}})\\""#,
+ value_to_replace
+ )) {
+ contents = re.replace_all(&contents, "$field").to_string();
+ } else {
+ eprintln!("Regex validation failed.");
+ }
+
+ let mut file = OpenOptions::new()
+ .write(true)
+ .truncate(true)
+ .open(&collection_path)?;
+
+ file.write_all(contents.as_bytes())?;
+ }
+
+ Ok((connector_name, Some(collection_path)))
+}
+
+pub fn export_collection(connector_name: &str, collection_dir_path: String) {
+ let collection_path = get_collection_path(connector_name);
+
+ let mut newman_command = Command::new("newman");
+ newman_command.args([
+ "dir-import".to_owned(),
+ collection_dir_path,
+ "-o".to_owned(),
+ collection_path.clone(),
+ ]);
+
+ match newman_command.spawn().and_then(|mut child| child.wait()) {
+ Ok(exit_status) => {
+ if exit_status.success() {
+ println!("Conversion of collection from directory structure to json successful!");
+ } else {
+ eprintln!("Conversion of collection from directory structure to json failed!");
+ exit(exit_status.code().unwrap_or(1));
+ }
+ }
+ Err(err) => {
+ eprintln!("Failed to execute dir-import: {:?}", err);
+ exit(1);
+ }
}
}
diff --git a/postman/collection-dir/aci/Health check/New Request/request.json b/postman/collection-dir/aci/Health check/New Request/request.json
index e40e9396178..ce92926c776 100644
--- a/postman/collection-dir/aci/Health check/New Request/request.json
+++ b/postman/collection-dir/aci/Health check/New Request/request.json
@@ -1,13 +1,6 @@
{
"method": "GET",
- "header": [
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- }
- ],
+ "header": [],
"url": {
"raw": "{{baseUrl}}/health",
"host": ["{{baseUrl}}"],
diff --git a/postman/collection-dir/adyen_uk/Health check/New Request/request.json b/postman/collection-dir/adyen_uk/Health check/New Request/request.json
index e40e9396178..ce92926c776 100644
--- a/postman/collection-dir/adyen_uk/Health check/New Request/request.json
+++ b/postman/collection-dir/adyen_uk/Health check/New Request/request.json
@@ -1,13 +1,6 @@
{
"method": "GET",
- "header": [
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- }
- ],
+ "header": [],
"url": {
"raw": "{{baseUrl}}/health",
"host": ["{{baseUrl}}"],
diff --git a/postman/collection-dir/airwallex/Health check/New Request/request.json b/postman/collection-dir/airwallex/Health check/New Request/request.json
index e40e9396178..ce92926c776 100644
--- a/postman/collection-dir/airwallex/Health check/New Request/request.json
+++ b/postman/collection-dir/airwallex/Health check/New Request/request.json
@@ -1,13 +1,6 @@
{
"method": "GET",
- "header": [
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- }
- ],
+ "header": [],
"url": {
"raw": "{{baseUrl}}/health",
"host": ["{{baseUrl}}"],
diff --git a/postman/collection-dir/authorizedotnet/Health check/New Request/request.json b/postman/collection-dir/authorizedotnet/Health check/New Request/request.json
index e40e9396178..ce92926c776 100644
--- a/postman/collection-dir/authorizedotnet/Health check/New Request/request.json
+++ b/postman/collection-dir/authorizedotnet/Health check/New Request/request.json
@@ -1,13 +1,6 @@
{
"method": "GET",
- "header": [
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- }
- ],
+ "header": [],
"url": {
"raw": "{{baseUrl}}/health",
"host": ["{{baseUrl}}"],
diff --git a/postman/collection-dir/bambora/Health check/New Request/request.json b/postman/collection-dir/bambora/Health check/New Request/request.json
index e40e9396178..ce92926c776 100644
--- a/postman/collection-dir/bambora/Health check/New Request/request.json
+++ b/postman/collection-dir/bambora/Health check/New Request/request.json
@@ -1,13 +1,6 @@
{
"method": "GET",
- "header": [
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- }
- ],
+ "header": [],
"url": {
"raw": "{{baseUrl}}/health",
"host": ["{{baseUrl}}"],
diff --git a/postman/collection-dir/bambora_3ds/Health check/New Request/request.json b/postman/collection-dir/bambora_3ds/Health check/New Request/request.json
index e40e9396178..ce92926c776 100644
--- a/postman/collection-dir/bambora_3ds/Health check/New Request/request.json
+++ b/postman/collection-dir/bambora_3ds/Health check/New Request/request.json
@@ -1,13 +1,6 @@
{
"method": "GET",
- "header": [
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- }
- ],
+ "header": [],
"url": {
"raw": "{{baseUrl}}/health",
"host": ["{{baseUrl}}"],
diff --git a/postman/collection-dir/bankofamerica/Health check/New Request/request.json b/postman/collection-dir/bankofamerica/Health check/New Request/request.json
index 4cc8d4b1a96..ce92926c776 100644
--- a/postman/collection-dir/bankofamerica/Health check/New Request/request.json
+++ b/postman/collection-dir/bankofamerica/Health check/New Request/request.json
@@ -1,20 +1,9 @@
{
"method": "GET",
- "header": [
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- }
- ],
+ "header": [],
"url": {
"raw": "{{baseUrl}}/health",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "health"
- ]
+ "host": ["{{baseUrl}}"],
+ "path": ["health"]
}
}
diff --git a/postman/collection-dir/bluesnap/Health check/New Request/request.json b/postman/collection-dir/bluesnap/Health check/New Request/request.json
index e40e9396178..ce92926c776 100644
--- a/postman/collection-dir/bluesnap/Health check/New Request/request.json
+++ b/postman/collection-dir/bluesnap/Health check/New Request/request.json
@@ -1,13 +1,6 @@
{
"method": "GET",
- "header": [
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- }
- ],
+ "header": [],
"url": {
"raw": "{{baseUrl}}/health",
"host": ["{{baseUrl}}"],
diff --git a/postman/collection-dir/braintree/Health check/New Request/request.json b/postman/collection-dir/braintree/Health check/New Request/request.json
index e40e9396178..ce92926c776 100644
--- a/postman/collection-dir/braintree/Health check/New Request/request.json
+++ b/postman/collection-dir/braintree/Health check/New Request/request.json
@@ -1,13 +1,6 @@
{
"method": "GET",
- "header": [
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- }
- ],
+ "header": [],
"url": {
"raw": "{{baseUrl}}/health",
"host": ["{{baseUrl}}"],
diff --git a/postman/collection-dir/checkout/Health check/New Request/request.json b/postman/collection-dir/checkout/Health check/New Request/request.json
index 4cc8d4b1a96..ce92926c776 100644
--- a/postman/collection-dir/checkout/Health check/New Request/request.json
+++ b/postman/collection-dir/checkout/Health check/New Request/request.json
@@ -1,20 +1,9 @@
{
"method": "GET",
- "header": [
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- }
- ],
+ "header": [],
"url": {
"raw": "{{baseUrl}}/health",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "health"
- ]
+ "host": ["{{baseUrl}}"],
+ "path": ["health"]
}
}
diff --git a/postman/collection-dir/forte/Health check/New Request/request.json b/postman/collection-dir/forte/Health check/New Request/request.json
index e40e9396178..ce92926c776 100644
--- a/postman/collection-dir/forte/Health check/New Request/request.json
+++ b/postman/collection-dir/forte/Health check/New Request/request.json
@@ -1,13 +1,6 @@
{
"method": "GET",
- "header": [
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- }
- ],
+ "header": [],
"url": {
"raw": "{{baseUrl}}/health",
"host": ["{{baseUrl}}"],
diff --git a/postman/collection-dir/globalpay/Health check/New Request/request.json b/postman/collection-dir/globalpay/Health check/New Request/request.json
index e40e9396178..ce92926c776 100644
--- a/postman/collection-dir/globalpay/Health check/New Request/request.json
+++ b/postman/collection-dir/globalpay/Health check/New Request/request.json
@@ -1,13 +1,6 @@
{
"method": "GET",
- "header": [
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- }
- ],
+ "header": [],
"url": {
"raw": "{{baseUrl}}/health",
"host": ["{{baseUrl}}"],
diff --git a/postman/collection-dir/hyperswitch/Health check/New Request/request.json b/postman/collection-dir/hyperswitch/Health check/New Request/request.json
index e40e9396178..ce92926c776 100644
--- a/postman/collection-dir/hyperswitch/Health check/New Request/request.json
+++ b/postman/collection-dir/hyperswitch/Health check/New Request/request.json
@@ -1,13 +1,6 @@
{
"method": "GET",
- "header": [
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- }
- ],
+ "header": [],
"url": {
"raw": "{{baseUrl}}/health",
"host": ["{{baseUrl}}"],
diff --git a/postman/collection-dir/mollie/Health check/New Request/request.json b/postman/collection-dir/mollie/Health check/New Request/request.json
index e40e9396178..ce92926c776 100644
--- a/postman/collection-dir/mollie/Health check/New Request/request.json
+++ b/postman/collection-dir/mollie/Health check/New Request/request.json
@@ -1,13 +1,6 @@
{
"method": "GET",
- "header": [
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- }
- ],
+ "header": [],
"url": {
"raw": "{{baseUrl}}/health",
"host": ["{{baseUrl}}"],
diff --git a/postman/collection-dir/multisafepay/Health check/New Request/request.json b/postman/collection-dir/multisafepay/Health check/New Request/request.json
index e40e9396178..ce92926c776 100644
--- a/postman/collection-dir/multisafepay/Health check/New Request/request.json
+++ b/postman/collection-dir/multisafepay/Health check/New Request/request.json
@@ -1,13 +1,6 @@
{
"method": "GET",
- "header": [
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- }
- ],
+ "header": [],
"url": {
"raw": "{{baseUrl}}/health",
"host": ["{{baseUrl}}"],
diff --git a/postman/collection-dir/nexinets/Health check/New Request/request.json b/postman/collection-dir/nexinets/Health check/New Request/request.json
index e40e9396178..ce92926c776 100644
--- a/postman/collection-dir/nexinets/Health check/New Request/request.json
+++ b/postman/collection-dir/nexinets/Health check/New Request/request.json
@@ -1,13 +1,6 @@
{
"method": "GET",
- "header": [
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- }
- ],
+ "header": [],
"url": {
"raw": "{{baseUrl}}/health",
"host": ["{{baseUrl}}"],
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9-Update amount with automatic capture/Payments - Confirm/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9-Update amount with automatic capture/Payments - Confirm/request.json
index 6c99817eb04..7b72495e5c4 100644
--- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9-Update amount with automatic capture/Payments - Confirm/request.json
+++ b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9-Update amount with automatic capture/Payments - Confirm/request.json
@@ -29,12 +29,7 @@
"key": "Accept",
"value": "application/json"
},
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- },
+ ,
{
"key": "publishable_key",
"value": "",
@@ -79,14 +74,8 @@
},
"url": {
"raw": "{{baseUrl}}/payments/:id/confirm",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments",
- ":id",
- "confirm"
- ],
+ "host": ["{{baseUrl}}"],
+ "path": ["payments", ":id", "confirm"],
"variable": [
{
"key": "id",
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9-Update amount with automatic capture/Payments - Update/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9-Update amount with automatic capture/Payments - Update/request.json
index 2d931088d18..bad52859824 100644
--- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9-Update amount with automatic capture/Payments - Update/request.json
+++ b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9-Update amount with automatic capture/Payments - Update/request.json
@@ -18,18 +18,14 @@
}
},
"raw_json_formatted": {
- "amount": "{{another_random_number}}"
+ "amount": "{{another_random_number}}",
+ "amount_to_capture": "{{another_random_number}}"
}
},
"url": {
"raw": "{{baseUrl}}/payments/:id",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments",
- ":id"
- ],
+ "host": ["{{baseUrl}}"],
+ "path": ["payments", ":id"],
"variable": [
{
"key": "id",
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9a-Update amount with manual capture/Payments - Confirm/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9a-Update amount with manual capture/Payments - Confirm/request.json
index 6c99817eb04..7b72495e5c4 100644
--- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9a-Update amount with manual capture/Payments - Confirm/request.json
+++ b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9a-Update amount with manual capture/Payments - Confirm/request.json
@@ -29,12 +29,7 @@
"key": "Accept",
"value": "application/json"
},
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- },
+ ,
{
"key": "publishable_key",
"value": "",
@@ -79,14 +74,8 @@
},
"url": {
"raw": "{{baseUrl}}/payments/:id/confirm",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments",
- ":id",
- "confirm"
- ],
+ "host": ["{{baseUrl}}"],
+ "path": ["payments", ":id", "confirm"],
"variable": [
{
"key": "id",
diff --git a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9a-Update amount with manual capture/Payments - Update/request.json b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9a-Update amount with manual capture/Payments - Update/request.json
index 2d931088d18..bad52859824 100644
--- a/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9a-Update amount with manual capture/Payments - Update/request.json
+++ b/postman/collection-dir/nmi/Flow Testcases/Happy Cases/Scenario9a-Update amount with manual capture/Payments - Update/request.json
@@ -18,18 +18,14 @@
}
},
"raw_json_formatted": {
- "amount": "{{another_random_number}}"
+ "amount": "{{another_random_number}}",
+ "amount_to_capture": "{{another_random_number}}"
}
},
"url": {
"raw": "{{baseUrl}}/payments/:id",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments",
- ":id"
- ],
+ "host": ["{{baseUrl}}"],
+ "path": ["payments", ":id"],
"variable": [
{
"key": "id",
diff --git a/postman/collection-dir/nmi/Health check/New Request/request.json b/postman/collection-dir/nmi/Health check/New Request/request.json
index 4cc8d4b1a96..ce92926c776 100644
--- a/postman/collection-dir/nmi/Health check/New Request/request.json
+++ b/postman/collection-dir/nmi/Health check/New Request/request.json
@@ -1,20 +1,9 @@
{
"method": "GET",
- "header": [
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- }
- ],
+ "header": [],
"url": {
"raw": "{{baseUrl}}/health",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "health"
- ]
+ "host": ["{{baseUrl}}"],
+ "path": ["health"]
}
}
diff --git a/postman/collection-dir/payme/Health check/New Request/request.json b/postman/collection-dir/payme/Health check/New Request/request.json
index e40e9396178..ce92926c776 100644
--- a/postman/collection-dir/payme/Health check/New Request/request.json
+++ b/postman/collection-dir/payme/Health check/New Request/request.json
@@ -1,13 +1,6 @@
{
"method": "GET",
- "header": [
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- }
- ],
+ "header": [],
"url": {
"raw": "{{baseUrl}}/health",
"host": ["{{baseUrl}}"],
diff --git a/postman/collection-dir/paypal/Health check/New Request/request.json b/postman/collection-dir/paypal/Health check/New Request/request.json
index e40e9396178..ce92926c776 100644
--- a/postman/collection-dir/paypal/Health check/New Request/request.json
+++ b/postman/collection-dir/paypal/Health check/New Request/request.json
@@ -1,13 +1,6 @@
{
"method": "GET",
- "header": [
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- }
- ],
+ "header": [],
"url": {
"raw": "{{baseUrl}}/health",
"host": ["{{baseUrl}}"],
diff --git a/postman/collection-dir/powertranz/Health check/New Request/request.json b/postman/collection-dir/powertranz/Health check/New Request/request.json
index e40e9396178..ce92926c776 100644
--- a/postman/collection-dir/powertranz/Health check/New Request/request.json
+++ b/postman/collection-dir/powertranz/Health check/New Request/request.json
@@ -1,13 +1,6 @@
{
"method": "GET",
- "header": [
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- }
- ],
+ "header": [],
"url": {
"raw": "{{baseUrl}}/health",
"host": ["{{baseUrl}}"],
diff --git a/postman/collection-dir/rapyd/Health check/New Request/request.json b/postman/collection-dir/rapyd/Health check/New Request/request.json
index e40e9396178..ce92926c776 100644
--- a/postman/collection-dir/rapyd/Health check/New Request/request.json
+++ b/postman/collection-dir/rapyd/Health check/New Request/request.json
@@ -1,13 +1,6 @@
{
"method": "GET",
- "header": [
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- }
- ],
+ "header": [],
"url": {
"raw": "{{baseUrl}}/health",
"host": ["{{baseUrl}}"],
diff --git a/postman/collection-dir/shift4/Health check/New Request/request.json b/postman/collection-dir/shift4/Health check/New Request/request.json
index e40e9396178..ce92926c776 100644
--- a/postman/collection-dir/shift4/Health check/New Request/request.json
+++ b/postman/collection-dir/shift4/Health check/New Request/request.json
@@ -1,13 +1,6 @@
{
"method": "GET",
- "header": [
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- }
- ],
+ "header": [],
"url": {
"raw": "{{baseUrl}}/health",
"host": ["{{baseUrl}}"],
diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update address and List Payment method/List Payment Methods for a Merchant-copy/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update address and List Payment method/List Payment Methods for a Merchant-copy/request.json
index fed600e09cd..dfe421f512f 100644
--- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update address and List Payment method/List Payment Methods for a Merchant-copy/request.json
+++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update address and List Payment method/List Payment Methods for a Merchant-copy/request.json
@@ -24,23 +24,12 @@
{
"key": "Accept",
"value": "application/json"
- },
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
}
],
"url": {
"raw": "{{baseUrl}}/account/payment_methods?client_secret={{client_secret}}",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "account",
- "payment_methods"
- ],
+ "host": ["{{baseUrl}}"],
+ "path": ["account", "payment_methods"],
"query": [
{
"key": "client_secret",
diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update address and List Payment method/List Payment Methods for a Merchant/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update address and List Payment method/List Payment Methods for a Merchant/request.json
index fed600e09cd..dfe421f512f 100644
--- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update address and List Payment method/List Payment Methods for a Merchant/request.json
+++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario22- Update address and List Payment method/List Payment Methods for a Merchant/request.json
@@ -24,23 +24,12 @@
{
"key": "Accept",
"value": "application/json"
- },
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
}
],
"url": {
"raw": "{{baseUrl}}/account/payment_methods?client_secret={{client_secret}}",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "account",
- "payment_methods"
- ],
+ "host": ["{{baseUrl}}"],
+ "path": ["account", "payment_methods"],
"query": [
{
"key": "client_secret",
diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23- Update Amount/Payments - Confirm/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23- Update Amount/Payments - Confirm/request.json
index 5b0c090f2be..5a51941cf64 100644
--- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23- Update Amount/Payments - Confirm/request.json
+++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23- Update Amount/Payments - Confirm/request.json
@@ -29,12 +29,7 @@
"key": "Accept",
"value": "application/json"
},
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- },
+ ,
{
"key": "publishable_key",
"value": "",
diff --git a/postman/collection-dir/stripe/Health check/New Request/request.json b/postman/collection-dir/stripe/Health check/New Request/request.json
index e40e9396178..ce92926c776 100644
--- a/postman/collection-dir/stripe/Health check/New Request/request.json
+++ b/postman/collection-dir/stripe/Health check/New Request/request.json
@@ -1,13 +1,6 @@
{
"method": "GET",
- "header": [
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- }
- ],
+ "header": [],
"url": {
"raw": "{{baseUrl}}/health",
"host": ["{{baseUrl}}"],
diff --git a/postman/collection-dir/trustpay/Health check/New Request/request.json b/postman/collection-dir/trustpay/Health check/New Request/request.json
index e40e9396178..ce92926c776 100644
--- a/postman/collection-dir/trustpay/Health check/New Request/request.json
+++ b/postman/collection-dir/trustpay/Health check/New Request/request.json
@@ -1,13 +1,6 @@
{
"method": "GET",
- "header": [
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- }
- ],
+ "header": [],
"url": {
"raw": "{{baseUrl}}/health",
"host": ["{{baseUrl}}"],
diff --git a/postman/collection-dir/volt/Health check/New Request/request.json b/postman/collection-dir/volt/Health check/New Request/request.json
index 4cc8d4b1a96..ce92926c776 100644
--- a/postman/collection-dir/volt/Health check/New Request/request.json
+++ b/postman/collection-dir/volt/Health check/New Request/request.json
@@ -1,20 +1,9 @@
{
"method": "GET",
- "header": [
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- }
- ],
+ "header": [],
"url": {
"raw": "{{baseUrl}}/health",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "health"
- ]
+ "host": ["{{baseUrl}}"],
+ "path": ["health"]
}
}
diff --git a/postman/collection-dir/wise/Health check/Health/request.json b/postman/collection-dir/wise/Health check/Health/request.json
index e40e9396178..ce92926c776 100644
--- a/postman/collection-dir/wise/Health check/Health/request.json
+++ b/postman/collection-dir/wise/Health check/Health/request.json
@@ -1,13 +1,6 @@
{
"method": "GET",
- "header": [
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- }
- ],
+ "header": [],
"url": {
"raw": "{{baseUrl}}/health",
"host": ["{{baseUrl}}"],
diff --git a/postman/collection-dir/worldline/Health check/New Request/request.json b/postman/collection-dir/worldline/Health check/New Request/request.json
index e40e9396178..ce92926c776 100644
--- a/postman/collection-dir/worldline/Health check/New Request/request.json
+++ b/postman/collection-dir/worldline/Health check/New Request/request.json
@@ -1,13 +1,6 @@
{
"method": "GET",
- "header": [
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- }
- ],
+ "header": [],
"url": {
"raw": "{{baseUrl}}/health",
"host": ["{{baseUrl}}"],
diff --git a/postman/collection-dir/zen/Health check/New Request/request.json b/postman/collection-dir/zen/Health check/New Request/request.json
index 9b836ff05cb..24ea5a4157a 100644
--- a/postman/collection-dir/zen/Health check/New Request/request.json
+++ b/postman/collection-dir/zen/Health check/New Request/request.json
@@ -3,14 +3,7 @@
"type": "noauth"
},
"method": "GET",
- "header": [
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- }
- ],
+ "header": [],
"url": {
"raw": "{{baseUrl}}/health",
"host": ["{{baseUrl}}"],
|
2024-02-24T17:47:27Z
|
## Type of Change
<!-- Put an `x` in the boxes that apply -->
- [ ] Bugfix
- [ ] New feature
- [ ] Enhancement
- [x] Refactoring
- [ ] Dependency updates
- [ ] Documentation
- [x] CI/CD
## Description
<!-- Describe your changes in detail -->
This PR refactors test_utils crate's `newman_runner` to support dynamic values through postman variables.
The main issue with `newman-dir` is that in order to export the collection, the variables must be of type string (Example: Variable value must be of type `"{{value}}"` and not `{{value}}`) without which the user cannot import or export the collection in directory format which is a bummer.
With this refactor, we've introduced a validation to look after `connector_name` and if it is `nmi` or `powertranz`, we'll be doing the collection refactor in run time (collection refactor here means that before the collection is run, we'll be updating the json collection file by removing the double quotes in the integer values (`amount`) at least in 40+ places) which is later restored after the collection is run.
With this change, we'll again be using `run` command to run the collections instead of `dir-run` going forward.
This also added some complexity with how we're running tests for `custom_headers` and removed that part of code from all the existing collections.
### 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).
-->
In order to run NMI collection which is updated here at #3805, this change is needed.
This PR should also close #3806.
## 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)?
-->
In #3805, the tests ran without any issues. Adding the screenshot below:
<img width="485" alt="image" src="https://github.com/juspay/hyperswitch/assets/69745008/7c925fb8-b6b0-4eac-9657-ee3c181c6b70">
Yet another validation: https://github.com/juspay/hyperswitch/actions/runs/8092287211/job/22112758729?pr=3807 (i know why it failed, outdated collection-json file which will be updated on next release after this pr is merged)
## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
6b078fa339b5404f7c730322bc8597cd1104ec15
|
|
juspay/hyperswitch
|
juspay__hyperswitch-3793
|
Bug: feat: add blacklist for roles
After a role is updated, the users who are using that role at that time should get new tokens. So, the role should be blacklisted.
|
diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs
index 3c3f01dc5f9..72f160990e5 100644
--- a/crates/router/src/consts.rs
+++ b/crates/router/src/consts.rs
@@ -70,6 +70,8 @@ pub const JWT_TOKEN_TIME_IN_SECS: u64 = 60 * 60 * 24 * 2; // 2 days
pub const USER_BLACKLIST_PREFIX: &str = "BU_";
+pub const ROLE_BLACKLIST_PREFIX: &str = "BR_";
+
#[cfg(feature = "email")]
pub const EMAIL_TOKEN_TIME_IN_SECS: u64 = 60 * 60 * 24; // 1 day
diff --git a/crates/router/src/core/user_role/role.rs b/crates/router/src/core/user_role/role.rs
index 7ce72779bbb..6edbda85bfd 100644
--- a/crates/router/src/core/user_role/role.rs
+++ b/crates/router/src/core/user_role/role.rs
@@ -12,7 +12,7 @@ use crate::{
core::errors::{StorageErrorExt, UserErrors, UserResponse},
routes::AppState,
services::{
- authentication::UserFromToken,
+ authentication::{blacklist, UserFromToken},
authorization::roles::{self, predefined_roles::PREDEFINED_ROLES},
ApplicationResponse,
},
@@ -219,5 +219,7 @@ pub async fn update_role(
.await
.to_duplicate_response(UserErrors::RoleNameAlreadyExists)?;
+ blacklist::insert_role_in_blacklist(&state, role_id).await?;
+
Ok(ApplicationResponse::StatusOk)
}
diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs
index 34153ef6e8f..455dc97d03e 100644
--- a/crates/router/src/services/authentication.rs
+++ b/crates/router/src/services/authentication.rs
@@ -13,6 +13,7 @@ use masking::ExposeInterface;
use masking::{PeekInterface, StrongSecret};
use serde::Serialize;
+use self::blacklist::BlackList;
use super::authorization::{self, permissions::Permission};
#[cfg(feature = "olap")]
use super::jwt;
@@ -334,7 +335,7 @@ where
state: &A,
) -> RouterResult<(UserWithoutMerchantFromToken, AuthenticationType)> {
let payload = parse_jwt_payload::<A, UserAuthToken>(request_headers, state).await?;
- if blacklist::check_user_in_blacklist(state, &payload.user_id, payload.exp).await? {
+ if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
@@ -499,7 +500,7 @@ where
state: &A,
) -> RouterResult<((), AuthenticationType)> {
let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
- if blacklist::check_user_in_blacklist(state, &payload.user_id, payload.exp).await? {
+ if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
@@ -528,7 +529,7 @@ where
state: &A,
) -> RouterResult<(UserFromToken, AuthenticationType)> {
let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
- if blacklist::check_user_in_blacklist(state, &payload.user_id, payload.exp).await? {
+ if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
@@ -566,7 +567,7 @@ where
state: &A,
) -> RouterResult<((), AuthenticationType)> {
let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
- if blacklist::check_user_in_blacklist(state, &payload.user_id, payload.exp).await? {
+ if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
@@ -609,7 +610,7 @@ where
state: &A,
) -> RouterResult<(AuthenticationData, AuthenticationType)> {
let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
- if blacklist::check_user_in_blacklist(state, &payload.user_id, payload.exp).await? {
+ if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
@@ -659,7 +660,7 @@ where
state: &A,
) -> RouterResult<(AuthenticationDataWithUserId, AuthenticationType)> {
let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
- if blacklist::check_user_in_blacklist(state, &payload.user_id, payload.exp).await? {
+ if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
@@ -710,7 +711,7 @@ where
state: &A,
) -> RouterResult<(UserFromToken, AuthenticationType)> {
let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
- if blacklist::check_user_in_blacklist(state, &payload.user_id, payload.exp).await? {
+ if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
@@ -741,7 +742,7 @@ where
state: &A,
) -> RouterResult<((), AuthenticationType)> {
let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
- if blacklist::check_user_in_blacklist(state, &payload.user_id, payload.exp).await? {
+ if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
diff --git a/crates/router/src/services/authentication/blacklist.rs b/crates/router/src/services/authentication/blacklist.rs
index 325ef29bad3..346e563ee32 100644
--- a/crates/router/src/services/authentication/blacklist.rs
+++ b/crates/router/src/services/authentication/blacklist.rs
@@ -5,10 +5,11 @@ use common_utils::date_time;
use error_stack::{IntoReport, ResultExt};
use redis_interface::RedisConnectionPool;
+use super::{AuthToken, UserAuthToken};
#[cfg(feature = "email")]
use crate::consts::{EMAIL_TOKEN_BLACKLIST_PREFIX, EMAIL_TOKEN_TIME_IN_SECS};
use crate::{
- consts::{JWT_TOKEN_TIME_IN_SECS, USER_BLACKLIST_PREFIX},
+ consts::{JWT_TOKEN_TIME_IN_SECS, ROLE_BLACKLIST_PREFIX, USER_BLACKLIST_PREFIX},
core::errors::{ApiErrorResponse, RouterResult},
routes::app::AppStateInfo,
};
@@ -34,6 +35,22 @@ pub async fn insert_user_in_blacklist(state: &AppState, user_id: &str) -> UserRe
.change_context(UserErrors::InternalServerError)
}
+#[cfg(feature = "olap")]
+pub async fn insert_role_in_blacklist(state: &AppState, role_id: &str) -> UserResult<()> {
+ let role_blacklist_key = format!("{}{}", ROLE_BLACKLIST_PREFIX, role_id);
+ let expiry =
+ expiry_to_i64(JWT_TOKEN_TIME_IN_SECS).change_context(UserErrors::InternalServerError)?;
+ let redis_conn = get_redis_connection(state).change_context(UserErrors::InternalServerError)?;
+ redis_conn
+ .set_key_with_expiry(
+ role_blacklist_key.as_str(),
+ date_time::now_unix_timestamp(),
+ expiry,
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)
+}
+
pub async fn check_user_in_blacklist<A: AppStateInfo>(
state: &A,
user_id: &str,
@@ -49,6 +66,21 @@ pub async fn check_user_in_blacklist<A: AppStateInfo>(
.map(|timestamp| timestamp.map_or(false, |timestamp| timestamp > token_issued_at))
}
+pub async fn check_role_in_blacklist<A: AppStateInfo>(
+ state: &A,
+ role_id: &str,
+ token_expiry: u64,
+) -> RouterResult<bool> {
+ let token = format!("{}{}", ROLE_BLACKLIST_PREFIX, role_id);
+ let token_issued_at = expiry_to_i64(token_expiry - JWT_TOKEN_TIME_IN_SECS)?;
+ let redis_conn = get_redis_connection(state)?;
+ redis_conn
+ .get_key::<Option<i64>>(token.as_str())
+ .await
+ .change_context(ApiErrorResponse::InternalServerError)
+ .map(|timestamp| timestamp.map_or(false, |timestamp| timestamp > token_issued_at))
+}
+
#[cfg(feature = "email")]
pub async fn insert_email_token_in_blacklist(state: &AppState, token: &str) -> UserResult<()> {
let redis_conn = get_redis_connection(state).change_context(UserErrors::InternalServerError)?;
@@ -90,3 +122,33 @@ fn expiry_to_i64(expiry: u64) -> RouterResult<i64> {
.into_report()
.change_context(ApiErrorResponse::InternalServerError)
}
+
+#[async_trait::async_trait]
+pub trait BlackList {
+ async fn check_in_blacklist<A>(&self, state: &A) -> RouterResult<bool>
+ where
+ A: AppStateInfo + Sync;
+}
+
+#[async_trait::async_trait]
+impl BlackList for AuthToken {
+ async fn check_in_blacklist<A>(&self, state: &A) -> RouterResult<bool>
+ where
+ A: AppStateInfo + Sync,
+ {
+ Ok(
+ check_user_in_blacklist(state, &self.user_id, self.exp).await?
+ || check_role_in_blacklist(state, &self.role_id, self.exp).await?,
+ )
+ }
+}
+
+#[async_trait::async_trait]
+impl BlackList for UserAuthToken {
+ async fn check_in_blacklist<A>(&self, state: &A) -> RouterResult<bool>
+ where
+ A: AppStateInfo + Sync,
+ {
+ check_user_in_blacklist(state, &self.user_id, self.exp).await
+ }
+}
|
2024-02-23T07:21:31Z
|
## 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 ability to blacklist roles to stop JWTs after a role is changed.
### 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 #3793
## 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)?
-->
Postman.
To get JWT of admin, you have to singup/create a new account. Or you can use a JWT of org_admin user.
1. Create a role
```
curl --location 'http://localhost:8080/user/role' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer JWT of Admin' \
--data '{
"role_name": "custom_role",
"groups": ["users_view"],
"role_scope": "merchant"
}'
```
Response should be 200 OK
This api will create a new custom role. This role can be assigned to people to restrict them.
2. Get the list of roles
```
curl --location 'http://localhost:8080/user/role/list' \
--header 'Authorization: Bearer JWT of Admin'
```
In the response you will find newly created role
```
[
{
"role_id": "role_of8p9odNmf2puQVhQemT",
"permissions": [
"MerchantAccountRead",
"UsersRead"
],
"role_name": "custom_role",
"role_scope": "merchant"
}
]
```
This api is called to get the details of the role that was perviously created.
3. Update a user in the merchant in that merchant account to this newly created role
```
curl --location 'http://localhost:8080/user/user/invite' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer JWT of Admin' \
--data-raw '{
"email": "email of other user in different merchant account",
"name": "user name",
"role_id": "role_of8p9odNmf2puQVhQemT"
}'
```
Response will be 200 OK.
You can use the details you got from the previous api and invite some other person into your org, this will automatically create a new user if user doesn't exist.
4. Login as the user who got invited
```
curl --location 'http://localhost:8080/user/signin' \
--header 'Content-Type: application/json' \
--data-raw '{
"email": "email of user who got udpated",
"password": "password"
}'
```
```
{
"token": "JWT of user who got updated",
"merchant_id": "merchant_id",
"name": "user name",
"email": "email of user who got updated",
"verification_days_left": null,
"user_role": "role_of8p9odNmf2puQVhQemT"
}
```
Use the credentials of the person who was invited to login and save the JWT.
5. Invite a new user with the role_id that was created previously using admin JWT
```
curl --location --request PUT 'http://localhost:8080/user/role/role_of8p9odNmf2puQVhQemT' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer JWT of Admin' \
--data '{
"groups": ["users_view", "users_manage"]
}'
```
Response will be 200 OK.
This api should be hit with Admin JWT again (not the invited user), this will update the role that we created earlier.
6. Try to use the token of the invited user which we saved earlier and hit this api and it will throw an error.
```
curl --location 'http://localhost:8080/user/user/invite' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer JWT of invited user that was saved previously' \
--data-raw '{
"email": "email of other user in different merchant account",
"name": "user name",
"role_id": "role_of8p9odNmf2puQVhQemT"
}'
```
```
{
"error": {
"type": "invalid_request",
"message": "Access forbidden, invalid JWT token was used",
"code": "IR_17"
}
}
```
## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
21d2b6ee2cacecc6da3a3c8ef07dedfb417752b0
|
|
juspay/hyperswitch
|
juspay__hyperswitch-3785
|
Bug: [FEATURE] : [Cybersource] mask pii information in connector request and response
### Feature Description
Mask pii information passed and received in the connector request and response
### Possible Implementation
Refactor all sensitive response and request fields secret
### 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/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs
index 4bb28439b7f..14f8b2a7f99 100644
--- a/crates/router/src/connector/cybersource/transformers.rs
+++ b/crates/router/src/connector/cybersource/transformers.rs
@@ -2,7 +2,7 @@ use api_models::payments;
use base64::Engine;
use common_utils::{ext_traits::ValueExt, pii};
use error_stack::{IntoReport, ResultExt};
-use masking::{PeekInterface, Secret};
+use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use serde_json::Value;
@@ -259,9 +259,9 @@ pub struct ProcessingInformation {
pub struct CybersourceConsumerAuthInformation {
ucaf_collection_indicator: Option<String>,
cavv: Option<String>,
- ucaf_authentication_data: Option<String>,
+ ucaf_authentication_data: Option<Secret<String>>,
xid: Option<String>,
- directory_server_transaction_id: Option<String>,
+ directory_server_transaction_id: Option<Secret<String>>,
specification_version: Option<String>,
}
#[derive(Debug, Serialize)]
@@ -385,7 +385,7 @@ pub enum PaymentInformation {
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CybersoucrePaymentInstrument {
- id: String,
+ id: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
@@ -1071,7 +1071,7 @@ impl
) -> Result<Self, Self::Error> {
let processing_information = ProcessingInformation::try_from((item, None, None))?;
let payment_instrument = CybersoucrePaymentInstrument {
- id: connector_mandate_id,
+ id: connector_mandate_id.into(),
};
let email = item.router_data.request.get_email()?;
let bill_to = build_bill_to(item.router_data.get_billing()?, email)?;
@@ -1491,7 +1491,7 @@ pub struct ClientRiskInformation {
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ClientRiskInformationRules {
- name: String,
+ name: Secret<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
@@ -1592,7 +1592,7 @@ fn get_payment_response(
.token_information
.clone()
.map(|token_info| types::MandateReference {
- connector_mandate_id: Some(token_info.payment_instrument.id),
+ connector_mandate_id: Some(token_info.payment_instrument.id.expose()),
payment_method_id: None,
});
Ok(types::PaymentsResponseData::TransactionResponse {
@@ -1941,10 +1941,10 @@ pub enum CybersourceAuthEnrollmentStatus {
pub struct CybersourceConsumerAuthValidateResponse {
ucaf_collection_indicator: Option<String>,
cavv: Option<String>,
- ucaf_authentication_data: Option<String>,
+ ucaf_authentication_data: Option<Secret<String>>,
xid: Option<String>,
specification_version: Option<String>,
- directory_server_transaction_id: Option<String>,
+ directory_server_transaction_id: Option<Secret<String>>,
indicator: Option<String>,
}
@@ -1956,7 +1956,7 @@ pub struct CybersourceThreeDSMetadata {
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CybersourceConsumerAuthInformationEnrollmentResponse {
- access_token: Option<String>,
+ access_token: Option<Secret<String>>,
step_up_url: Option<String>,
//Added to segregate the three_ds_data in a separate struct
#[serde(flatten)]
@@ -2044,9 +2044,9 @@ impl<F>
.consumer_authentication_information
.step_up_url,
) {
- (Some(access_token), Some(step_up_url)) => {
+ (Some(token), Some(step_up_url)) => {
Some(services::RedirectForm::CybersourceConsumerAuth {
- access_token,
+ access_token: token.expose(),
step_up_url,
})
}
@@ -2241,7 +2241,7 @@ impl<F, T>
CybersourceSetupMandatesResponse::ClientReferenceInformation(info_response) => {
let mandate_reference = info_response.token_information.clone().map(|token_info| {
types::MandateReference {
- connector_mandate_id: Some(token_info.payment_instrument.id),
+ connector_mandate_id: Some(token_info.payment_instrument.id.expose()),
payment_method_id: None,
}
});
@@ -2655,7 +2655,7 @@ impl
client_risk_information.rules.map(|rules| {
rules
.iter()
- .map(|risk_info| format!(" , {}", risk_info.name))
+ .map(|risk_info| format!(" , {}", risk_info.name.clone().expose()))
.collect::<Vec<String>>()
.join("")
})
|
2024-02-22T12:14:42Z
|
## 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 -->
Mask pii information passed and received in the connector request and response for Cybersource.
## Test Case
1.a. Create a 3DS payment
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: dev_sJlLjo5AQkfrDpPH0IEmB0gKzEgOLRr4CnI0PeHyePVJmCEoww6B9bkUjcVFyIFF' \
--data-raw '{
"amount": 0,
"currency": "PLN",
"confirm": true,
"business_country": "US",
"business_label": "default",
"capture_method": "automatic",
"customer_id": "abc",
"capture_on": "2022-09-10T10:11:12Z",
"authentication_type": "three_ds",
"return_url": "https://hs-payments-test.netlify.app/payments",
"email": "arjun.karthik@juspay.in",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"statement_descriptor_name": "Juspay",
"statement_descriptor_suffix": "Router",
"setup_future_usage": "off_session",
"payment_method": "card",
"payment_method_type": "credit",
"payment_type": "setup_mandate",
"payment_method_data": {
"card": {
"card_number": "4622943127013705",
"card_exp_month": "12",
"card_exp_year": "2030",
"card_holder_name": "joseph Doe",
"card_cvc": "838"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "CA",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "New York",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "8056594427",
"country_code": "+91"
}
},
"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": "125.0.0.1"
},
"metadata": {
"order_details": {
"product_name": "Apple iphone 15",
"quantity": 1,
"amount": 3200,
"account_name": "transaction_processing"
}
},
"mandate_data": {
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "13.232.74.226",
"user_agent": "amet irure esse"
}
}
, "mandate_type": {
"multi_use": {
"amount": 700,
"currency": "USD"
}
}
}
}'
```
1.b. Check if all the sensitive data in the `masked_response` is masked
```
curl --location '{{base_url}}/analytics/v1/connector_event_logs?type=Payment&payment_id={{payment_id}}' \
--header 'sec-ch-ua: "Not A(Brand";v="99", "Google Chrome";v="121", "Chromium";v="121"' \
--header 'sec-ch-ua-mobile: ?0' \
--header 'authorization: Bearer JWT_token' \
--header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36' \
--header 'Content-Type: application/json' \
--header 'Referer: https://integ.hyperswitch.io/' \
--header 'api-key: {{api-key}}' \
--header 'sec-ch-ua-platform: "macOS"'
```
masked_response should be
```
{\\\"id\\\":\\\"7089429038836063404953\\\",\\\"status\\\":\\\"AUTHORIZED\\\",\\\"clientReferenceInformation\\\":{\\\"code\\\":\\\"pay_BxnKPq7bjemAWr97xyk3_1\\\"},\\\"processorInformation\\\":{\\\"avs\\\":{\\\"code\\\":\\\"Y\\\",\\\"codeRaw\\\":\\\"Y\\\"}},\\\"riskInformation\\\":{\\\"rules\\\":null},\\\"tokenInformation\\\":{\\\"paymentInstrument\\\":{\\\"id\\\":\\\"*** alloc::string::String ***\\\"}}
```
2.a. Check if sensitive data is masked - MIT
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key:{{api-key}}' \
--data '{
"amount": 700,
"currency": "USD",
"off_session": true,
"confirm": true,
"capture_method": "automatic",
"description": "Initiated by merchant",
"mandate_id": "{{mandate_id}}",
"customer_id": "abc",
"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"
}
}
}'
```
2.b. Check if all the sensitive data in the `masked_response` is masked
```
curl --location '{{base_url}}/analytics/v1/connector_event_logs?type=Payment&payment_id={{payment_id}}' \
--header 'sec-ch-ua: "Not A(Brand";v="99", "Google Chrome";v="121", "Chromium";v="121"' \
--header 'sec-ch-ua-mobile: ?0' \
--header 'authorization: Bearer JWT_token' \
--header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36' \
--header 'Content-Type: application/json' \
--header 'Referer: https://integ.hyperswitch.io/' \
--header 'api-key: {{api-key}}' \
--header 'sec-ch-ua-platform: "macOS"'
```
Response should be
```
"masked_response\":\"{\\\"id\\\":\\\"7089431984486510104951\\\",\\\"status\\\":\\\"AUTHORIZED\\\",\\\"clientReferenceInformation\\\":{\\\"code\\\":\\\"pay_TL8q8JuBwqoQ94bQBYY5_1\\\"},\\\"processorInformation\\\":{\\\"avs\\\":{\\\"code\\\":\\\"Y\\\",\\\"codeRaw\\\":\\\"Y\\\"}}
```
Impact Area
> Cybersource 3ds mandate payment flow
> Cybersource MIT flow
## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
75c633fc7c37341177597041ccbcdfc3cf9e236f
|
|
juspay/hyperswitch
|
juspay__hyperswitch-3813
|
Bug: Update Hyperswitch Token construction to include MIT details
- To begin with we will store Payment Method ID along with the Locker ID in the token instead
|
diff --git a/crates/diesel_models/src/payment_method.rs b/crates/diesel_models/src/payment_method.rs
index d8b46c1932e..f9767e2939b 100644
--- a/crates/diesel_models/src/payment_method.rs
+++ b/crates/diesel_models/src/payment_method.rs
@@ -33,6 +33,7 @@ pub struct PaymentMethod {
pub payment_method_issuer_code: Option<storage_enums::PaymentMethodIssuerCode>,
pub metadata: Option<pii::SecretSerdeValue>,
pub payment_method_data: Option<Encryption>,
+ pub locker_id: Option<String>,
}
#[derive(Clone, Debug, Eq, PartialEq, Insertable, Queryable, router_derive::DebugAsDisplay)]
@@ -59,6 +60,7 @@ pub struct PaymentMethodNew {
pub last_modified: PrimitiveDateTime,
pub metadata: Option<pii::SecretSerdeValue>,
pub payment_method_data: Option<Encryption>,
+ pub locker_id: Option<String>,
}
impl Default for PaymentMethodNew {
@@ -69,6 +71,7 @@ impl Default for PaymentMethodNew {
customer_id: String::default(),
merchant_id: String::default(),
payment_method_id: String::default(),
+ locker_id: Option::default(),
payment_method: storage_enums::PaymentMethod::default(),
payment_method_type: Option::default(),
payment_method_issuer: Option::default(),
diff --git a/crates/diesel_models/src/query/payment_method.rs b/crates/diesel_models/src/query/payment_method.rs
index b1ea3ee388a..298db2a234b 100644
--- a/crates/diesel_models/src/query/payment_method.rs
+++ b/crates/diesel_models/src/query/payment_method.rs
@@ -44,6 +44,15 @@ impl PaymentMethod {
.await
}
+ #[instrument(skip(conn))]
+ pub async fn find_by_locker_id(conn: &PgPooledConn, locker_id: &str) -> StorageResult<Self> {
+ generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
+ conn,
+ dsl::locker_id.eq(locker_id.to_owned()),
+ )
+ .await
+ }
+
#[instrument(skip(conn))]
pub async fn find_by_payment_method_id(
conn: &PgPooledConn,
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index 5093f0df7d0..3364e560277 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -828,6 +828,8 @@ diesel::table! {
payment_method_issuer_code -> Nullable<PaymentMethodIssuerCode>,
metadata -> Nullable<Json>,
payment_method_data -> Nullable<Bytea>,
+ #[max_length = 64]
+ locker_id -> Nullable<Varchar>,
}
}
diff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rs
index 9442bf2ff34..be306112873 100644
--- a/crates/router/src/core/customers.rs
+++ b/crates/router/src/core/customers.rs
@@ -218,7 +218,7 @@ pub async fn delete_customer(
&state,
&req.customer_id,
&merchant_account.merchant_id,
- &pm.payment_method_id,
+ pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id),
)
.await
.switch()?;
diff --git a/crates/router/src/core/locker_migration.rs b/crates/router/src/core/locker_migration.rs
index 2ebec569b38..1347bb8ffd0 100644
--- a/crates/router/src/core/locker_migration.rs
+++ b/crates/router/src/core/locker_migration.rs
@@ -83,9 +83,13 @@ pub async fn call_to_locker(
.into_iter()
.filter(|pm| matches!(pm.payment_method, storage_enums::PaymentMethod::Card))
{
- let card =
- cards::get_card_from_locker(state, customer_id, merchant_id, &pm.payment_method_id)
- .await;
+ let card = cards::get_card_from_locker(
+ state,
+ customer_id,
+ merchant_id,
+ pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id),
+ )
+ .await;
let card = match card {
Ok(card) => card,
@@ -127,7 +131,7 @@ pub async fn call_to_locker(
customer_id.to_string(),
merchant_account,
api_enums::LockerChoice::HyperswitchCardVault,
- Some(&pm.payment_method_id),
+ Some(pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id)),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs
index c1617fa77c9..bdbd9b02d9e 100644
--- a/crates/router/src/core/payment_methods.rs
+++ b/crates/router/src/core/payment_methods.rs
@@ -155,7 +155,7 @@ impl PaymentMethodRetrieve for Oss {
storage::PaymentTokenData::Permanent(card_token) => {
helpers::retrieve_card_with_permanent_token(
state,
- &card_token.token,
+ card_token.locker_id.as_ref().unwrap_or(&card_token.token),
payment_intent,
card_token_data,
)
@@ -166,7 +166,7 @@ impl PaymentMethodRetrieve for Oss {
storage::PaymentTokenData::PermanentCard(card_token) => {
helpers::retrieve_card_with_permanent_token(
state,
- &card_token.token,
+ card_token.locker_id.as_ref().unwrap_or(&card_token.token),
payment_intent,
card_token_data,
)
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index dbd8efcd1cf..7bf956be9ff 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -76,6 +76,7 @@ pub async fn create_payment_method(
req: &api::PaymentMethodCreate,
customer_id: &str,
payment_method_id: &str,
+ locker_id: Option<String>,
merchant_id: &str,
pm_metadata: Option<serde_json::Value>,
payment_method_data: Option<Encryption>,
@@ -90,6 +91,7 @@ pub async fn create_payment_method(
customer_id: customer_id.to_string(),
merchant_id: merchant_id.to_string(),
payment_method_id: payment_method_id.to_string(),
+ locker_id,
payment_method: req.payment_method,
payment_method_type: req.payment_method_type,
payment_method_issuer: req.payment_method_issuer.clone(),
@@ -131,6 +133,65 @@ pub fn store_default_payment_method(
(payment_method_response, None)
}
+#[instrument(skip_all)]
+pub async fn get_or_insert_payment_method(
+ db: &dyn db::StorageInterface,
+ req: api::PaymentMethodCreate,
+ resp: &mut api::PaymentMethodResponse,
+ merchant_account: &domain::MerchantAccount,
+ customer_id: &str,
+ key_store: &domain::MerchantKeyStore,
+) -> errors::RouterResult<diesel_models::PaymentMethod> {
+ let mut payment_method_id = resp.payment_method_id.clone();
+ let mut locker_id = None;
+ let payment_method = {
+ let existing_pm_by_pmid = db.find_payment_method(&payment_method_id).await;
+
+ if let Err(err) = existing_pm_by_pmid {
+ if err.current_context().is_db_not_found() {
+ locker_id = Some(payment_method_id.clone());
+ let existing_pm_by_locker_id = db
+ .find_payment_method_by_locker_id(&payment_method_id)
+ .await;
+
+ match &existing_pm_by_locker_id {
+ Ok(pm) => payment_method_id = pm.payment_method_id.clone(),
+ Err(_) => payment_method_id = generate_id(consts::ID_LENGTH, "pm"),
+ };
+ existing_pm_by_locker_id
+ } else {
+ Err(err)
+ }
+ } else {
+ existing_pm_by_pmid
+ }
+ };
+ resp.payment_method_id = payment_method_id.to_owned();
+
+ match payment_method {
+ Ok(pm) => Ok(pm),
+ Err(err) => {
+ if err.current_context().is_db_not_found() {
+ insert_payment_method(
+ db,
+ resp,
+ req,
+ key_store,
+ &merchant_account.merchant_id,
+ customer_id,
+ resp.metadata.clone().map(|val| val.expose()),
+ locker_id,
+ )
+ .await
+ } else {
+ Err(err)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Error while finding payment method")
+ }
+ }
+ }
+}
+
#[instrument(skip_all)]
pub async fn add_payment_method(
state: routes::AppState,
@@ -182,40 +243,41 @@ pub async fn add_payment_method(
)),
};
- let (resp, duplication_check) = response?;
+ let (mut resp, duplication_check) = response?;
match duplication_check {
Some(duplication_check) => match duplication_check {
payment_methods::DataDuplicationCheck::Duplicated => {
- let existing_pm = db.find_payment_method(&resp.payment_method_id).await;
-
- if let Err(err) = existing_pm {
- if err.current_context().is_db_not_found() {
- insert_payment_method(
- db,
- &resp,
- req,
- key_store,
- merchant_id,
- &customer_id,
- None,
- )
- .await
- } else {
- Err(err)
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Error while finding payment method")
- }?
- };
+ get_or_insert_payment_method(
+ db,
+ req.clone(),
+ &mut resp,
+ merchant_account,
+ &customer_id,
+ key_store,
+ )
+ .await?;
}
-
payment_methods::DataDuplicationCheck::MetaDataChanged => {
if let Some(card) = req.card.clone() {
+ let existing_pm = get_or_insert_payment_method(
+ db,
+ req.clone(),
+ &mut resp,
+ merchant_account,
+ &customer_id,
+ key_store,
+ )
+ .await?;
+
delete_card_from_locker(
&state,
&customer_id,
merchant_id,
- &resp.payment_method_id,
+ existing_pm
+ .locker_id
+ .as_ref()
+ .unwrap_or(&existing_pm.payment_method_id),
)
.await?;
@@ -226,7 +288,12 @@ pub async fn add_payment_method(
customer_id.clone(),
merchant_account,
api::enums::LockerChoice::HyperswitchCardVault,
- Some(&resp.payment_method_id),
+ Some(
+ existing_pm
+ .locker_id
+ .as_ref()
+ .unwrap_or(&existing_pm.payment_method_id),
+ ),
)
.await;
@@ -243,69 +310,46 @@ pub async fn add_payment_method(
.attach_printable("Failed while updating card metadata changes"))?
};
- let existing_pm = db.find_payment_method(&resp.payment_method_id).await;
- match existing_pm {
- Ok(pm) => {
- let updated_card = Some(api::CardDetailFromLocker {
- scheme: None,
- last4_digits: Some(card.card_number.clone().get_last4()),
- issuer_country: None,
- card_number: Some(card.card_number),
- expiry_month: Some(card.card_exp_month),
- expiry_year: Some(card.card_exp_year),
- card_token: None,
- card_fingerprint: None,
- card_holder_name: card.card_holder_name,
- nick_name: card.nick_name,
- card_network: None,
- card_isin: None,
- card_issuer: None,
- card_type: None,
- saved_to_locker: true,
- });
-
- let updated_pmd = updated_card.as_ref().map(|card| {
- PaymentMethodsData::Card(CardDetailsPaymentMethod::from(
- card.clone(),
- ))
- });
- let pm_data_encrypted =
- create_encrypted_payment_method_data(key_store, updated_pmd).await;
-
- let pm_update = storage::PaymentMethodUpdate::PaymentMethodDataUpdate {
- payment_method_data: pm_data_encrypted,
- };
-
- db.update_payment_method(pm, pm_update)
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to add payment method in db")?;
- }
- Err(err) => {
- if err.current_context().is_db_not_found() {
- insert_payment_method(
- db,
- &resp,
- req,
- key_store,
- merchant_id,
- &customer_id,
- None,
- )
- .await
- } else {
- Err(err)
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Error while finding payment method")
- }?;
- }
- }
+ let updated_card = Some(api::CardDetailFromLocker {
+ scheme: None,
+ last4_digits: Some(card.card_number.clone().get_last4()),
+ issuer_country: None,
+ card_number: Some(card.card_number),
+ expiry_month: Some(card.card_exp_month),
+ expiry_year: Some(card.card_exp_year),
+ card_token: None,
+ card_fingerprint: None,
+ card_holder_name: card.card_holder_name,
+ nick_name: card.nick_name,
+ card_network: None,
+ card_isin: None,
+ card_issuer: None,
+ card_type: None,
+ saved_to_locker: true,
+ });
+
+ let updated_pmd = updated_card.as_ref().map(|card| {
+ PaymentMethodsData::Card(CardDetailsPaymentMethod::from(card.clone()))
+ });
+ let pm_data_encrypted =
+ create_encrypted_payment_method_data(key_store, updated_pmd).await;
+
+ let pm_update = storage::PaymentMethodUpdate::PaymentMethodDataUpdate {
+ payment_method_data: pm_data_encrypted,
+ };
+
+ db.update_payment_method(existing_pm, pm_update)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to add payment method in db")?;
}
}
},
None => {
let pm_metadata = resp.metadata.as_ref().map(|data| data.peek());
+ let locker_id = Some(resp.payment_method_id);
+ resp.payment_method_id = generate_id(consts::ID_LENGTH, "pm");
insert_payment_method(
db,
&resp,
@@ -314,14 +358,16 @@ pub async fn add_payment_method(
merchant_id,
&customer_id,
pm_metadata.cloned(),
+ locker_id,
)
.await?;
}
- };
+ }
Ok(services::ApplicationResponse::Json(resp))
}
+#[allow(clippy::too_many_arguments)]
pub async fn insert_payment_method(
db: &dyn db::StorageInterface,
resp: &api::PaymentMethodResponse,
@@ -330,7 +376,8 @@ pub async fn insert_payment_method(
merchant_id: &str,
customer_id: &str,
pm_metadata: Option<serde_json::Value>,
-) -> errors::RouterResult<()> {
+ locker_id: Option<String>,
+) -> errors::RouterResult<diesel_models::PaymentMethod> {
let pm_card_details = resp
.card
.as_ref()
@@ -341,14 +388,13 @@ pub async fn insert_payment_method(
&req,
customer_id,
&resp.payment_method_id,
+ locker_id,
merchant_id,
pm_metadata,
pm_data_encrypted,
key_store,
)
- .await?;
-
- Ok(())
+ .await
}
#[instrument(skip_all)]
@@ -372,7 +418,7 @@ pub async fn update_customer_payment_method(
&state,
&pm.customer_id,
&pm.merchant_id,
- &pm.payment_method_id,
+ pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id),
)
.await?;
};
@@ -927,7 +973,7 @@ pub async fn mock_call_to_locker_hs<'a>(
duplication_check: None,
};
Ok(payment_methods::StoreCardResp {
- status: "SUCCESS".to_string(),
+ status: "Ok".to_string(),
error_code: None,
error_message: None,
payload: Some(payload),
@@ -1013,7 +1059,7 @@ pub async fn mock_delete_card_hs<'a>(
.await
.change_context(errors::VaultError::FetchCardFailed)?;
Ok(payment_methods::DeleteCardResp {
- status: "SUCCESS".to_string(),
+ status: "Ok".to_string(),
error_code: None,
error_message: None,
})
@@ -1032,7 +1078,7 @@ pub async fn mock_delete_card<'a>(
card_id: Some(locker_mock_up.card_id),
external_id: Some(locker_mock_up.external_id),
card_isin: None,
- status: "SUCCESS".to_string(),
+ status: "Ok".to_string(),
})
}
//------------------------------------------------------------------------------
@@ -2642,7 +2688,11 @@ pub async fn list_customer_payment_method(
(
card_details,
None,
- PaymentTokenData::permanent_card(pm.payment_method_id.clone()),
+ 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;
@@ -2662,7 +2712,7 @@ pub async fn list_customer_payment_method(
&token,
&pm.customer_id,
&pm.merchant_id,
- &pm.payment_method_id,
+ pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id),
)
.await?,
),
@@ -2902,7 +2952,7 @@ pub async fn get_card_details_from_locker(
state,
&pm.customer_id,
&pm.merchant_id,
- &pm.payment_method_id,
+ pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
@@ -3167,7 +3217,7 @@ pub async fn retrieve_payment_method(
&state,
&pm.customer_id,
&pm.merchant_id,
- &pm.payment_method_id,
+ pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
@@ -3217,11 +3267,11 @@ pub async fn delete_payment_method(
&state,
&key.customer_id,
&key.merchant_id,
- pm_id.payment_method_id.as_str(),
+ key.locker_id.as_ref().unwrap_or(&key.payment_method_id),
)
.await?;
- if response.status == "SUCCESS" {
+ if response.status == "Ok" {
logger::info!("Card From locker deleted Successfully!");
} else {
logger::error!("Error: Deleting Card From Locker!\n{:#?}", response);
diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs
index 57e46bc9769..6bad41630b5 100644
--- a/crates/router/src/core/payment_methods/transformers.rs
+++ b/crates/router/src/core/payment_methods/transformers.rs
@@ -397,46 +397,6 @@ pub fn mk_add_card_response_hs(
}
}
-pub fn mk_add_card_response(
- card: api::CardDetail,
- response: AddCardResponse,
- req: api::PaymentMethodCreate,
- merchant_id: &str,
-) -> api::PaymentMethodResponse {
- let mut card_number = card.card_number.peek().to_owned();
- let card = api::CardDetailFromLocker {
- scheme: None,
- last4_digits: Some(card_number.split_off(card_number.len() - 4)),
- issuer_country: None, // [#256] bin mapping
- card_number: Some(card.card_number),
- expiry_month: Some(card.card_exp_month),
- expiry_year: Some(card.card_exp_year),
- card_token: Some(response.external_id.into()), // [#256]
- card_fingerprint: Some(response.card_fingerprint),
- card_holder_name: card.card_holder_name,
- nick_name: card.nick_name,
- card_isin: None,
- card_issuer: None,
- card_network: None,
- card_type: None,
- saved_to_locker: true,
- };
- api::PaymentMethodResponse {
- merchant_id: merchant_id.to_owned(),
- customer_id: req.customer_id,
- payment_method_id: response.card_id,
- payment_method: req.payment_method,
- payment_method_type: req.payment_method_type,
- bank_transfer: None,
- card: Some(card),
- metadata: req.metadata,
- created: Some(common_utils::date_time::now()),
- recurring_enabled: false, // [#256]
- installment_payment_enabled: false, // [#256] Pending on discussion, and not stored in the card locker
- payment_experience: None, // [#256]
- }
-}
-
pub fn mk_add_card_request(
locker: &settings::Locker,
card: &api::CardDetail,
diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs
index 2d7a09bdae1..d08f0208500 100644
--- a/crates/router/src/core/payments/tokenization.rs
+++ b/crates/router/src/core/payments/tokenization.rs
@@ -6,6 +6,7 @@ use router_env::{instrument, tracing};
use super::helpers;
use crate::{
+ consts,
core::{
errors::{self, ConnectorErrorExt, RouterResult, StorageErrorExt},
mandate, payment_methods, payments,
@@ -19,7 +20,7 @@ use crate::{
domain,
storage::{self, enums as storage_enums},
},
- utils::OptionExt,
+ utils::{generate_id, OptionExt},
};
#[instrument(skip_all)]
@@ -85,7 +86,7 @@ where
.await?;
let merchant_id = &merchant_account.merchant_id;
- let locker_response = if !state.conf.locker.locker_enabled {
+ let (mut resp, duplication_check) = if !state.conf.locker.locker_enabled {
skip_saving_card_in_locker(
merchant_account,
payment_method_create_request.to_owned(),
@@ -100,9 +101,7 @@ where
.await?
};
- let duplication_check = locker_response.1;
-
- let pm_card_details = locker_response.0.card.as_ref().map(|card| {
+ let pm_card_details = resp.card.as_ref().map(|card| {
api::payment_methods::PaymentMethodsData::Card(CardDetailsPaymentMethod::from(
card.clone(),
))
@@ -115,13 +114,44 @@ where
)
.await;
+ let mut payment_method_id = resp.payment_method_id.clone();
+ let mut locker_id = None;
+
match duplication_check {
Some(duplication_check) => match duplication_check {
payment_methods::transformers::DataDuplicationCheck::Duplicated => {
- let existing_pm = db
- .find_payment_method(&locker_response.0.payment_method_id)
- .await;
- match existing_pm {
+ let payment_method = {
+ let existing_pm_by_pmid =
+ db.find_payment_method(&payment_method_id).await;
+
+ if let Err(err) = existing_pm_by_pmid {
+ if err.current_context().is_db_not_found() {
+ locker_id = Some(payment_method_id.clone());
+ let existing_pm_by_locker_id = db
+ .find_payment_method_by_locker_id(&payment_method_id)
+ .await;
+
+ match &existing_pm_by_locker_id {
+ Ok(pm) => {
+ payment_method_id = pm.payment_method_id.clone()
+ }
+ Err(_) => {
+ payment_method_id =
+ generate_id(consts::ID_LENGTH, "pm")
+ }
+ };
+ existing_pm_by_locker_id
+ } else {
+ Err(err)
+ }
+ } else {
+ existing_pm_by_pmid
+ }
+ };
+
+ resp.payment_method_id = payment_method_id;
+
+ match payment_method {
Ok(pm) => {
let pm_metadata = create_payment_method_metadata(
pm.metadata.as_ref(),
@@ -146,7 +176,8 @@ where
db,
&payment_method_create_request,
&customer.customer_id,
- &locker_response.0.payment_method_id,
+ &resp.payment_method_id,
+ locker_id,
merchant_id,
pm_metadata,
pm_data_encrypted,
@@ -165,22 +196,87 @@ where
}
payment_methods::transformers::DataDuplicationCheck::MetaDataChanged => {
if let Some(card) = payment_method_create_request.card.clone() {
+ let payment_method = {
+ let existing_pm_by_pmid =
+ db.find_payment_method(&payment_method_id).await;
+
+ if let Err(err) = existing_pm_by_pmid {
+ if err.current_context().is_db_not_found() {
+ locker_id = Some(payment_method_id.clone());
+ let existing_pm_by_locker_id = db
+ .find_payment_method_by_locker_id(
+ &payment_method_id,
+ )
+ .await;
+
+ match &existing_pm_by_locker_id {
+ Ok(pm) => {
+ payment_method_id = pm.payment_method_id.clone()
+ }
+ Err(_) => {
+ payment_method_id =
+ generate_id(consts::ID_LENGTH, "pm")
+ }
+ };
+ existing_pm_by_locker_id
+ } else {
+ Err(err)
+ }
+ } else {
+ existing_pm_by_pmid
+ }
+ };
+
+ resp.payment_method_id = payment_method_id;
+
+ let existing_pm =
+ match payment_method {
+ Ok(pm) => Ok(pm),
+ Err(err) => {
+ if err.current_context().is_db_not_found() {
+ payment_methods::cards::insert_payment_method(
+ db,
+ &resp,
+ payment_method_create_request.clone(),
+ key_store,
+ &merchant_account.merchant_id,
+ &customer.customer_id,
+ resp.metadata.clone().map(|val| val.expose()),
+ locker_id,
+ )
+ .await
+ } else {
+ Err(err)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Error while finding payment method")
+ }
+ }
+ }?;
+
payment_methods::cards::delete_card_from_locker(
state,
&customer.customer_id,
merchant_id,
- &locker_response.0.payment_method_id,
+ existing_pm
+ .locker_id
+ .as_ref()
+ .unwrap_or(&existing_pm.payment_method_id),
)
.await?;
let add_card_resp = payment_methods::cards::add_card_hs(
state,
- payment_method_create_request.clone(),
+ payment_method_create_request,
&card,
customer.customer_id.clone(),
merchant_account,
api::enums::LockerChoice::HyperswitchCardVault,
- Some(&locker_response.0.payment_method_id),
+ Some(
+ existing_pm
+ .locker_id
+ .as_ref()
+ .unwrap_or(&existing_pm.payment_method_id),
+ ),
)
.await;
@@ -188,7 +284,7 @@ where
logger::error!(vault_err=?err);
db.delete_payment_method_by_merchant_id_payment_method_id(
merchant_id,
- &locker_response.0.payment_method_id,
+ &resp.payment_method_id,
)
.await
.to_not_found_response(
@@ -201,90 +297,59 @@ where
))?
};
- let existing_pm = db
- .find_payment_method(&locker_response.0.payment_method_id)
+ let updated_card = Some(CardDetailFromLocker {
+ scheme: None,
+ last4_digits: Some(card.card_number.clone().get_last4()),
+ issuer_country: None,
+ card_number: Some(card.card_number),
+ expiry_month: Some(card.card_exp_month),
+ expiry_year: Some(card.card_exp_year),
+ card_token: None,
+ card_fingerprint: None,
+ card_holder_name: card.card_holder_name,
+ nick_name: card.nick_name,
+ card_network: None,
+ card_isin: None,
+ card_issuer: None,
+ card_type: None,
+ saved_to_locker: true,
+ });
+
+ let updated_pmd = updated_card.as_ref().map(|card| {
+ PaymentMethodsData::Card(CardDetailsPaymentMethod::from(
+ card.clone(),
+ ))
+ });
+ let pm_data_encrypted =
+ payment_methods::cards::create_encrypted_payment_method_data(
+ key_store,
+ updated_pmd,
+ )
.await;
- match existing_pm {
- Ok(pm) => {
- let updated_card = Some(CardDetailFromLocker {
- scheme: None,
- last4_digits: Some(
- card.card_number.clone().get_last4(),
- ),
- issuer_country: None,
- card_number: Some(card.card_number),
- expiry_month: Some(card.card_exp_month),
- expiry_year: Some(card.card_exp_year),
- card_token: None,
- card_fingerprint: None,
- card_holder_name: card.card_holder_name,
- nick_name: card.nick_name,
- card_network: None,
- card_isin: None,
- card_issuer: None,
- card_type: None,
- saved_to_locker: true,
- });
-
- let updated_pmd = updated_card.as_ref().map(|card| {
- PaymentMethodsData::Card(
- CardDetailsPaymentMethod::from(card.clone()),
- )
- });
- let pm_data_encrypted =
- payment_methods::cards::create_encrypted_payment_method_data(
- key_store,
- updated_pmd,
- )
- .await;
- let pm_update =
- storage::PaymentMethodUpdate::PaymentMethodDataUpdate {
- payment_method_data: pm_data_encrypted,
- };
+ let pm_update =
+ storage::PaymentMethodUpdate::PaymentMethodDataUpdate {
+ payment_method_data: pm_data_encrypted,
+ };
- db.update_payment_method(pm, pm_update)
- .await
- .change_context(
- errors::ApiErrorResponse::InternalServerError,
- )
- .attach_printable(
- "Failed to add payment method in db",
- )?;
- }
- Err(err) => {
- if err.current_context().is_db_not_found() {
- payment_methods::cards::insert_payment_method(
- db,
- &locker_response.0,
- payment_method_create_request,
- key_store,
- merchant_id,
- &customer.customer_id,
- None,
- )
- .await
- } else {
- Err(err)
- .change_context(
- errors::ApiErrorResponse::InternalServerError,
- )
- .attach_printable(
- "Error while finding payment method",
- )
- }?;
- }
- }
+ db.update_payment_method(existing_pm, pm_update)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to add payment method in db")?;
}
}
},
None => {
let pm_metadata = create_payment_method_metadata(None, connector_token)?;
+
+ locker_id = Some(resp.payment_method_id);
+ resp.payment_method_id = generate_id(consts::ID_LENGTH, "pm");
payment_methods::cards::create_payment_method(
db,
&payment_method_create_request,
&customer.customer_id,
- &locker_response.0.payment_method_id,
+ &resp.payment_method_id,
+ locker_id,
merchant_id,
pm_metadata,
pm_data_encrypted,
@@ -294,7 +359,7 @@ where
}
}
- Some(locker_response.0.payment_method_id)
+ Some(resp.payment_method_id)
} else {
None
};
diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs
index 7fb6fa3bde6..de57f8549db 100644
--- a/crates/router/src/core/payouts/helpers.rs
+++ b/crates/router/src/core/payouts/helpers.rs
@@ -78,9 +78,11 @@ pub async fn make_payout_method_data<'a>(
.attach_printable("failed to deserialize hyperswitch token data")?;
let payment_token = match payment_token_data {
- storage::PaymentTokenData::PermanentCard(storage::CardTokenData { token }) => {
- Some(token)
- }
+ storage::PaymentTokenData::PermanentCard(storage::CardTokenData {
+ locker_id,
+ token,
+ ..
+ }) => locker_id.or(Some(token)),
storage::PaymentTokenData::TemporaryGeneric(storage::GenericTokenData {
token,
}) => Some(token),
@@ -364,11 +366,13 @@ pub async fn save_payout_data_to_locker(
card_network: None,
};
+ let payment_method_id = common_utils::generate_id(crate::consts::ID_LENGTH, "pm");
cards::create_payment_method(
db,
&payment_method,
&payout_attempt.customer_id,
- &stored_resp.card_reference,
+ &payment_method_id,
+ Some(stored_resp.card_reference),
&merchant_account.merchant_id,
None,
card_details_encrypted,
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 78b95544ca1..9dbecd82485 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -1270,6 +1270,15 @@ impl PaymentMethodInterface for KafkaStore {
.await
}
+ async fn find_payment_method_by_locker_id(
+ &self,
+ locker_id: &str,
+ ) -> CustomResult<storage::PaymentMethod, errors::StorageError> {
+ self.diesel_store
+ .find_payment_method_by_locker_id(locker_id)
+ .await
+ }
+
async fn insert_payment_method(
&self,
m: storage::PaymentMethodNew,
diff --git a/crates/router/src/db/payment_method.rs b/crates/router/src/db/payment_method.rs
index b109d1fe5bd..4f4087f552e 100644
--- a/crates/router/src/db/payment_method.rs
+++ b/crates/router/src/db/payment_method.rs
@@ -15,6 +15,11 @@ pub trait PaymentMethodInterface {
payment_method_id: &str,
) -> CustomResult<storage::PaymentMethod, errors::StorageError>;
+ async fn find_payment_method_by_locker_id(
+ &self,
+ locker_id: &str,
+ ) -> CustomResult<storage::PaymentMethod, errors::StorageError>;
+
async fn find_payment_method_by_customer_id_merchant_id_list(
&self,
customer_id: &str,
@@ -52,6 +57,17 @@ impl PaymentMethodInterface for Store {
.into_report()
}
+ async fn find_payment_method_by_locker_id(
+ &self,
+ locker_id: &str,
+ ) -> CustomResult<storage::PaymentMethod, errors::StorageError> {
+ let conn = connection::pg_connection_read(self).await?;
+ storage::PaymentMethod::find_by_locker_id(&conn, locker_id)
+ .await
+ .map_err(Into::into)
+ .into_report()
+ }
+
async fn insert_payment_method(
&self,
payment_method_new: storage::PaymentMethodNew,
@@ -127,6 +143,25 @@ impl PaymentMethodInterface for MockDb {
}
}
+ async fn find_payment_method_by_locker_id(
+ &self,
+ locker_id: &str,
+ ) -> CustomResult<storage::PaymentMethod, errors::StorageError> {
+ let payment_methods = self.payment_methods.lock().await;
+ let payment_method = payment_methods
+ .iter()
+ .find(|pm| pm.locker_id == Some(locker_id.to_string()))
+ .cloned();
+
+ match payment_method {
+ Some(pm) => Ok(pm),
+ None => Err(errors::StorageError::ValueNotFound(
+ "cannot find payment method".to_string(),
+ )
+ .into()),
+ }
+ }
+
async fn insert_payment_method(
&self,
payment_method_new: storage::PaymentMethodNew,
@@ -142,6 +177,7 @@ impl PaymentMethodInterface for MockDb {
customer_id: payment_method_new.customer_id,
merchant_id: payment_method_new.merchant_id,
payment_method_id: payment_method_new.payment_method_id,
+ locker_id: payment_method_new.locker_id,
accepted_currency: payment_method_new.accepted_currency,
scheme: payment_method_new.scheme,
token: payment_method_new.token,
diff --git a/crates/router/src/types/api/mandates.rs b/crates/router/src/types/api/mandates.rs
index 051547dfa92..10c56973dd3 100644
--- a/crates/router/src/types/api/mandates.rs
+++ b/crates/router/src/types/api/mandates.rs
@@ -51,7 +51,10 @@ impl MandateResponseExt for MandateResponse {
state,
&payment_method.customer_id,
&payment_method.merchant_id,
- &payment_method.payment_method_id,
+ payment_method
+ .locker_id
+ .as_ref()
+ .unwrap_or(&payment_method.payment_method_id),
)
.await?;
diff --git a/crates/router/src/types/storage/payment_method.rs b/crates/router/src/types/storage/payment_method.rs
index 096303446dc..a787a4d932c 100644
--- a/crates/router/src/types/storage/payment_method.rs
+++ b/crates/router/src/types/storage/payment_method.rs
@@ -13,6 +13,8 @@ pub enum PaymentTokenKind {
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct CardTokenData {
+ pub payment_method_id: Option<String>,
+ pub locker_id: Option<String>,
pub token: String,
}
@@ -34,8 +36,16 @@ pub enum PaymentTokenData {
}
impl PaymentTokenData {
- pub fn permanent_card(token: String) -> Self {
- Self::PermanentCard(CardTokenData { token })
+ pub fn permanent_card(
+ payment_method_id: Option<String>,
+ locker_id: Option<String>,
+ token: String,
+ ) -> Self {
+ Self::PermanentCard(CardTokenData {
+ payment_method_id,
+ locker_id,
+ token,
+ })
}
pub fn temporary_generic(token: String) -> Self {
diff --git a/migrations/2024-02-20-142032_add_locker_id_to_payment_methods/down.sql b/migrations/2024-02-20-142032_add_locker_id_to_payment_methods/down.sql
new file mode 100644
index 00000000000..90eaebaf4da
--- /dev/null
+++ b/migrations/2024-02-20-142032_add_locker_id_to_payment_methods/down.sql
@@ -0,0 +1,3 @@
+-- This file should undo anything in `up.sql`
+
+ALTER TABLE payment_methods DROP COLUMN IF EXISTS locker_id;
diff --git a/migrations/2024-02-20-142032_add_locker_id_to_payment_methods/up.sql b/migrations/2024-02-20-142032_add_locker_id_to_payment_methods/up.sql
new file mode 100644
index 00000000000..516dc8a8818
--- /dev/null
+++ b/migrations/2024-02-20-142032_add_locker_id_to_payment_methods/up.sql
@@ -0,0 +1,3 @@
+-- Your SQL goes here
+
+ALTER TABLE payment_methods ADD COLUMN IF NOT EXISTS locker_id VARCHAR(64) DEFAULT NULL;
\ No newline at end of file
|
2024-02-21T17:18:08Z
|
## 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 we are mapping `locker_id` from locker to `payment_method_id` in Hyperswitch. This refactor involves changes to store the locker id in the `locker_id` column as opposed to the `payment_method_id` column, and store a unique ID in place of the `payment_method_id`. While reading the locker id, read from the `locker_id` column with `payment_method_id` as fallback.
### 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)?
-->
Sandbox testing -
* Should be tested similar to https://github.com/juspay/hyperswitch/pull/3146
* Test it for both old card already saved before this PR went in along with new card
* Both `/payment_methods` and `/payment` card flow has to be tested with metadata changes too. Everything should work fine
Test cases (`payment_methods` table) -
(Card 1): Db entry before this code changes :- `locker_id` should be null

(Card 1): MetaData updation :- Both `payment_method_id` and `locker_id` will remain same but with updated `payment_method_data`

(Card 2): Db entry when new card is added :- `locker_id` will now be the id from locker, `payment_method_id` will be nano_id

(Card 2): MetaData updation :- Both `payment_method_id` and `locker_id` will remain same but with updated `payment_method_data`

Redis entry (Local testing) -
Old card (both locker_id and payment_method_id will be same):

New card (payment_method_id will be nano_id and locker_id will be the id returned from locker):

## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
75c633fc7c37341177597041ccbcdfc3cf9e236f
|
|
juspay/hyperswitch
|
juspay__hyperswitch-3814
|
Bug: Allow off-session payments using Payment Method ID (only with API Key auth)
When a mandate is created on connector's end, we store the connector mandate details in our payment methods table. Now in order to make recurring payment with this, we basically have to do a token based payment where set the `setup_future_usage = off_session` and we list the payment methods of a customer and make a payment with payment token. But we should also allow off-session payments using payment method id without having to list customer payment methods. For this, we accept `off_session = true` and payment method id in the request and make a recurring mandate payment.
|
diff --git a/crates/api_models/src/mandates.rs b/crates/api_models/src/mandates.rs
index bd5c5b5a1a0..4adda0d9af4 100644
--- a/crates/api_models/src/mandates.rs
+++ b/crates/api_models/src/mandates.rs
@@ -113,3 +113,10 @@ pub struct MandateListConstraints {
#[serde(rename = "created_time.gte")]
pub created_time_gte: Option<PrimitiveDateTime>,
}
+
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
+#[serde(tag = "type", content = "data", rename_all = "snake_case")]
+pub enum RecurringDetails {
+ MandateId(String),
+ PaymentMethodId(String),
+}
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index ce2b1c3d68a..72592ec3cad 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -19,10 +19,8 @@ use url::Url;
use utoipa::ToSchema;
use crate::{
- admin, disputes,
- enums::{self as api_enums},
- ephemeral_key::EphemeralKeyCreateResponse,
- refunds,
+ admin, disputes, enums as api_enums, ephemeral_key::EphemeralKeyCreateResponse,
+ mandates::RecurringDetails, refunds,
};
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
@@ -459,6 +457,9 @@ pub struct PaymentsRequest {
/// Whether to perform external authentication (if applicable)
#[schema(example = true)]
pub request_external_three_ds_authentication: Option<bool>,
+
+ /// Details required for recurring payment
+ pub recurring_details: Option<RecurringDetails>,
}
impl PaymentsRequest {
@@ -3360,7 +3361,7 @@ pub struct PaymentsRedirectionResponse {
}
pub struct MandateValidationFields {
- pub mandate_id: Option<String>,
+ pub recurring_details: Option<RecurringDetails>,
pub confirm: Option<bool>,
pub customer_id: Option<String>,
pub mandate_data: Option<MandateData>,
@@ -3370,8 +3371,14 @@ pub struct MandateValidationFields {
impl From<&PaymentsRequest> for MandateValidationFields {
fn from(req: &PaymentsRequest) -> Self {
+ let recurring_details = req
+ .mandate_id
+ .clone()
+ .map(RecurringDetails::MandateId)
+ .or(req.recurring_details.clone());
+
Self {
- mandate_id: req.mandate_id.clone(),
+ recurring_details,
confirm: req.confirm,
customer_id: req
.customer
@@ -3389,7 +3396,7 @@ impl From<&PaymentsRequest> for MandateValidationFields {
impl From<&VerifyRequest> for MandateValidationFields {
fn from(req: &VerifyRequest) -> Self {
Self {
- mandate_id: None,
+ recurring_details: None,
confirm: Some(true),
customer_id: req.customer_id.clone(),
mandate_data: req.mandate_data.clone(),
diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs
index c8e89f2ee70..4a61a20d08d 100644
--- a/crates/openapi/src/openapi.rs
+++ b/crates/openapi/src/openapi.rs
@@ -410,6 +410,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::mandates::MandateRevokedResponse,
api_models::mandates::MandateResponse,
api_models::mandates::MandateCardDetails,
+ api_models::mandates::RecurringDetails,
api_models::ephemeral_key::EphemeralKeyCreateResponse,
api_models::payments::CustomerDetails,
api_models::payments::GiftCardData,
diff --git a/crates/router/src/core/mandate/helpers.rs b/crates/router/src/core/mandate/helpers.rs
index 150130ed9e5..704b7ae99f5 100644
--- a/crates/router/src/core/mandate/helpers.rs
+++ b/crates/router/src/core/mandate/helpers.rs
@@ -1,8 +1,14 @@
+use common_enums::enums;
use common_utils::errors::CustomResult;
+use data_models::mandates::MandateData;
use diesel_models::Mandate;
use error_stack::ResultExt;
-use crate::{core::errors, routes::AppState, types::domain};
+use crate::{
+ core::{errors, payments},
+ routes::AppState,
+ types::domain,
+};
pub async fn get_profile_id_for_mandate(
state: &AppState,
@@ -33,3 +39,14 @@ pub async fn get_profile_id_for_mandate(
}?;
Ok(profile_id)
}
+
+#[derive(Clone)]
+pub struct MandateGenericData {
+ pub token: Option<String>,
+ pub payment_method: Option<enums::PaymentMethod>,
+ pub payment_method_type: Option<enums::PaymentMethodType>,
+ pub mandate_data: Option<MandateData>,
+ pub recurring_mandate_payment_data: Option<payments::RecurringMandatePaymentData>,
+ pub mandate_connector: Option<payments::MandateConnectorDetails>,
+ pub payment_method_info: Option<diesel_models::PaymentMethod>,
+}
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 0a3a93923b7..e11a77496af 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -15,6 +15,7 @@ use std::{fmt::Debug, marker::PhantomData, ops::Deref, time::Instant, vec::IntoI
use api_models::{
self, enums,
+ mandates::RecurringDetails,
payments::{self as payments_api, HeaderPayload},
};
use common_utils::{ext_traits::AsyncExt, pii, types::Surcharge};
@@ -2263,6 +2264,7 @@ where
pub authorizations: Vec<diesel_models::authorization::Authorization>,
pub authentication: Option<storage::Authentication>,
pub frm_metadata: Option<serde_json::Value>,
+ pub recurring_details: Option<RecurringDetails>,
}
#[derive(Debug, Default, Clone)]
@@ -2907,7 +2909,7 @@ where
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Invalid connector name received")?;
- return decide_connector_for_token_based_mit_flow(
+ return decide_multiplex_connector_for_normal_or_recurring_payment(
payment_data,
routing_data,
connector_data,
@@ -2961,7 +2963,7 @@ where
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Invalid connector name received")?;
- return decide_connector_for_token_based_mit_flow(
+ return decide_multiplex_connector_for_normal_or_recurring_payment(
payment_data,
routing_data,
connector_data,
@@ -2980,24 +2982,26 @@ where
.await
}
-pub fn decide_connector_for_token_based_mit_flow<F: Clone>(
+pub fn decide_multiplex_connector_for_normal_or_recurring_payment<F: Clone>(
payment_data: &mut PaymentData<F>,
routing_data: &mut storage::RoutingData,
connectors: Vec<api::ConnectorData>,
) -> RouterResult<ConnectorCallType> {
- if let Some((storage_enums::FutureUsage::OffSession, _)) = payment_data
- .payment_intent
- .setup_future_usage
- .zip(payment_data.token_data.as_ref())
- {
- logger::debug!("performing routing for token-based MIT flow");
+ match (
+ payment_data.payment_intent.setup_future_usage,
+ payment_data.token_data.as_ref(),
+ payment_data.recurring_details.as_ref(),
+ ) {
+ (Some(storage_enums::FutureUsage::OffSession), Some(_), None)
+ | (None, None, Some(RecurringDetails::PaymentMethodId(_))) => {
+ logger::debug!("performing routing for token-based MIT flow");
- let payment_method_info = payment_data
- .payment_method_info
- .as_ref()
- .get_required_value("payment_method_info")?;
+ let payment_method_info = payment_data
+ .payment_method_info
+ .as_ref()
+ .get_required_value("payment_method_info")?;
- let connector_mandate_details = payment_method_info
+ let connector_mandate_details = payment_method_info
.connector_mandate_details
.clone()
.map(|details| {
@@ -3010,67 +3014,69 @@ pub fn decide_connector_for_token_based_mit_flow<F: Clone>(
.change_context(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)
.attach_printable("no eligible connector found for token-based MIT flow since there were no connector mandate details")?;
- let mut connector_choice = None;
- for connector_data in connectors {
- if let Some(merchant_connector_id) = connector_data.merchant_connector_id.as_ref() {
- if let Some(mandate_reference_record) =
- connector_mandate_details.get(merchant_connector_id)
- {
- connector_choice = Some((connector_data, mandate_reference_record.clone()));
- break;
+ let mut connector_choice = None;
+ for connector_data in connectors {
+ if let Some(merchant_connector_id) = connector_data.merchant_connector_id.as_ref() {
+ if let Some(mandate_reference_record) =
+ connector_mandate_details.get(merchant_connector_id)
+ {
+ connector_choice = Some((connector_data, mandate_reference_record.clone()));
+ break;
+ }
}
}
- }
- let (chosen_connector_data, mandate_reference_record) = connector_choice
- .get_required_value("connector_choice")
- .change_context(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)
- .attach_printable("no eligible connector found for token-based MIT payment")?;
+ let (chosen_connector_data, mandate_reference_record) = connector_choice
+ .get_required_value("connector_choice")
+ .change_context(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)
+ .attach_printable("no eligible connector found for token-based MIT payment")?;
- routing_data.routed_through = Some(chosen_connector_data.connector_name.to_string());
- #[cfg(feature = "connector_choice_mca_id")]
- {
- routing_data.merchant_connector_id =
- chosen_connector_data.merchant_connector_id.clone();
- }
+ routing_data.routed_through = Some(chosen_connector_data.connector_name.to_string());
+ #[cfg(feature = "connector_choice_mca_id")]
+ {
+ routing_data.merchant_connector_id =
+ chosen_connector_data.merchant_connector_id.clone();
+ }
- payment_data.mandate_id = Some(payments_api::MandateIds {
- mandate_id: None,
- mandate_reference_id: Some(payments_api::MandateReferenceId::ConnectorMandateId(
- payments_api::ConnectorMandateReferenceId {
- connector_mandate_id: Some(
- mandate_reference_record.connector_mandate_id.clone(),
- ),
- payment_method_id: Some(payment_method_info.payment_method_id.clone()),
- update_history: None,
- },
- )),
- });
-
- payment_data.recurring_mandate_payment_data = Some(RecurringMandatePaymentData {
- payment_method_type: mandate_reference_record.payment_method_type,
- original_payment_authorized_amount: mandate_reference_record
- .original_payment_authorized_amount,
- original_payment_authorized_currency: mandate_reference_record
- .original_payment_authorized_currency,
- });
-
- Ok(api::ConnectorCallType::PreDetermined(chosen_connector_data))
- } else {
- let first_choice = connectors
- .first()
- .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)
- .into_report()
- .attach_printable("no eligible connector found for payment")?
- .clone();
-
- routing_data.routed_through = Some(first_choice.connector_name.to_string());
- #[cfg(feature = "connector_choice_mca_id")]
- {
- routing_data.merchant_connector_id = first_choice.merchant_connector_id;
+ payment_data.mandate_id = Some(payments_api::MandateIds {
+ mandate_id: None,
+ mandate_reference_id: Some(payments_api::MandateReferenceId::ConnectorMandateId(
+ payments_api::ConnectorMandateReferenceId {
+ connector_mandate_id: Some(
+ mandate_reference_record.connector_mandate_id.clone(),
+ ),
+ payment_method_id: Some(payment_method_info.payment_method_id.clone()),
+ update_history: None,
+ },
+ )),
+ });
+
+ payment_data.recurring_mandate_payment_data = Some(RecurringMandatePaymentData {
+ payment_method_type: mandate_reference_record.payment_method_type,
+ original_payment_authorized_amount: mandate_reference_record
+ .original_payment_authorized_amount,
+ original_payment_authorized_currency: mandate_reference_record
+ .original_payment_authorized_currency,
+ });
+
+ Ok(api::ConnectorCallType::PreDetermined(chosen_connector_data))
}
+ _ => {
+ let first_choice = connectors
+ .first()
+ .ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)
+ .into_report()
+ .attach_printable("no eligible connector found for payment")?
+ .clone();
+
+ routing_data.routed_through = Some(first_choice.connector_name.to_string());
+ #[cfg(feature = "connector_choice_mca_id")]
+ {
+ routing_data.merchant_connector_id = first_choice.merchant_connector_id;
+ }
- Ok(api::ConnectorCallType::Retryable(connectors))
+ Ok(api::ConnectorCallType::Retryable(connectors))
+ }
}
}
@@ -3291,7 +3297,11 @@ where
match transaction_data {
TransactionData::Payment(payment_data) => {
- decide_connector_for_token_based_mit_flow(payment_data, routing_data, connector_data)
+ decide_multiplex_connector_for_normal_or_recurring_payment(
+ payment_data,
+ routing_data,
+ connector_data,
+ )
}
#[cfg(feature = "payouts")]
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 7eab4c0d26a..e9cefbf8aed 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -1,6 +1,9 @@
use std::borrow::Cow;
-use api_models::payments::{CardToken, GetPaymentMethodType, RequestSurchargeDetails};
+use api_models::{
+ mandates::RecurringDetails,
+ payments::{CardToken, GetPaymentMethodType, RequestSurchargeDetails},
+};
use base64::Engine;
use common_utils::{
ext_traits::{AsyncExt, ByteSliceExt, Encode, ValueExt},
@@ -34,6 +37,7 @@ use crate::{
consts::{self, BASE64_ENGINE},
core::{
errors::{self, CustomResult, RouterResult, StorageErrorExt},
+ mandate::helpers::MandateGenericData,
payment_methods::{cards, vault, PaymentMethodRetrieve},
payments,
pm_auth::retrieve_payment_method_from_auth_service,
@@ -414,59 +418,117 @@ pub async fn get_token_pm_type_mandate_details(
mandate_type: Option<api::MandateTransactionType>,
merchant_account: &domain::MerchantAccount,
merchant_key_store: &domain::MerchantKeyStore,
-) -> RouterResult<(
- Option<String>,
- Option<storage_enums::PaymentMethod>,
- Option<storage_enums::PaymentMethodType>,
- Option<MandateData>,
- Option<payments::RecurringMandatePaymentData>,
- Option<payments::MandateConnectorDetails>,
-)> {
+) -> RouterResult<MandateGenericData> {
let mandate_data = request.mandate_data.clone().map(MandateData::foreign_from);
- match mandate_type {
- Some(api::MandateTransactionType::NewMandateTransaction) => {
- let setup_mandate = mandate_data.clone().get_required_value("mandate_data")?;
- Ok((
- request.payment_token.to_owned(),
- request.payment_method,
- request.payment_method_type,
- Some(setup_mandate),
- None,
- None,
- ))
- }
+ let (
+ payment_token,
+ payment_method,
+ payment_method_type,
+ mandate_data,
+ recurring_payment_data,
+ mandate_connector_details,
+ payment_method_info,
+ ) = match mandate_type {
+ Some(api::MandateTransactionType::NewMandateTransaction) => (
+ request.payment_token.to_owned(),
+ request.payment_method,
+ request.payment_method_type,
+ Some(mandate_data.clone().get_required_value("mandate_data")?),
+ None,
+ None,
+ None,
+ ),
Some(api::MandateTransactionType::RecurringMandateTransaction) => {
- let (
- token_,
- payment_method_,
- recurring_mandate_payment_data,
- payment_method_type_,
- mandate_connector,
- ) = get_token_for_recurring_mandate(
- state,
- request,
- merchant_account,
- merchant_key_store,
- )
- .await?;
- Ok((
- token_,
- payment_method_,
- payment_method_type_.or(request.payment_method_type),
- None,
- recurring_mandate_payment_data,
- mandate_connector,
- ))
+ match &request.recurring_details {
+ Some(recurring_details) => match recurring_details {
+ RecurringDetails::MandateId(mandate_id) => {
+ let mandate_generic_data = get_token_for_recurring_mandate(
+ state,
+ request,
+ merchant_account,
+ merchant_key_store,
+ mandate_id.to_owned(),
+ )
+ .await?;
+
+ (
+ mandate_generic_data.token,
+ mandate_generic_data.payment_method,
+ mandate_generic_data
+ .payment_method_type
+ .or(request.payment_method_type),
+ None,
+ mandate_generic_data.recurring_mandate_payment_data,
+ mandate_generic_data.mandate_connector,
+ None,
+ )
+ }
+ RecurringDetails::PaymentMethodId(payment_method_id) => {
+ let payment_method_info = state
+ .store
+ .find_payment_method(payment_method_id)
+ .await
+ .to_not_found_response(
+ errors::ApiErrorResponse::PaymentMethodNotFound,
+ )?;
+
+ (
+ None,
+ Some(payment_method_info.payment_method),
+ payment_method_info.payment_method_type,
+ None,
+ None,
+ None,
+ Some(payment_method_info),
+ )
+ }
+ },
+ None => {
+ let mandate_id = request
+ .mandate_id
+ .clone()
+ .get_required_value("mandate_id")?;
+ let mandate_generic_data = get_token_for_recurring_mandate(
+ state,
+ request,
+ merchant_account,
+ merchant_key_store,
+ mandate_id,
+ )
+ .await?;
+ (
+ mandate_generic_data.token,
+ mandate_generic_data.payment_method,
+ mandate_generic_data
+ .payment_method_type
+ .or(request.payment_method_type),
+ None,
+ mandate_generic_data.recurring_mandate_payment_data,
+ mandate_generic_data.mandate_connector,
+ None,
+ )
+ }
+ }
}
- None => Ok((
+ None => (
request.payment_token.to_owned(),
request.payment_method,
request.payment_method_type,
mandate_data,
None,
None,
- )),
- }
+ None,
+ ),
+ };
+ Ok(MandateGenericData {
+ token: payment_token,
+ payment_method,
+ payment_method_type,
+ mandate_data,
+ recurring_mandate_payment_data: recurring_payment_data,
+ mandate_connector: mandate_connector_details,
+ payment_method_info,
+ })
}
pub async fn get_token_for_recurring_mandate(
@@ -474,15 +536,9 @@ pub async fn get_token_for_recurring_mandate(
req: &api::PaymentsRequest,
merchant_account: &domain::MerchantAccount,
merchant_key_store: &domain::MerchantKeyStore,
-) -> RouterResult<(
- Option<String>,
- Option<storage_enums::PaymentMethod>,
- Option<payments::RecurringMandatePaymentData>,
- Option<storage_enums::PaymentMethodType>,
- Option<payments::MandateConnectorDetails>,
-)> {
+ mandate_id: String,
+) -> RouterResult<MandateGenericData> {
let db = &*state.store;
- let mandate_id = req.mandate_id.clone().get_required_value("mandate_id")?;
let mandate = db
.find_mandate_by_merchant_id_mandate_id(&merchant_account.merchant_id, mandate_id.as_str())
@@ -566,29 +622,33 @@ pub async fn get_token_for_recurring_mandate(
}
};
- Ok((
- Some(token),
- Some(payment_method.payment_method),
- Some(payments::RecurringMandatePaymentData {
+ Ok(MandateGenericData {
+ token: Some(token),
+ payment_method: Some(payment_method.payment_method),
+ recurring_mandate_payment_data: Some(payments::RecurringMandatePaymentData {
payment_method_type,
original_payment_authorized_amount,
original_payment_authorized_currency,
}),
- payment_method.payment_method_type,
- Some(mandate_connector_details),
- ))
+ payment_method_type: payment_method.payment_method_type,
+ mandate_connector: Some(mandate_connector_details),
+ mandate_data: None,
+ payment_method_info: None,
+ })
} else {
- Ok((
- None,
- Some(payment_method.payment_method),
- Some(payments::RecurringMandatePaymentData {
+ Ok(MandateGenericData {
+ token: None,
+ payment_method: Some(payment_method.payment_method),
+ recurring_mandate_payment_data: Some(payments::RecurringMandatePaymentData {
payment_method_type,
original_payment_authorized_amount,
original_payment_authorized_currency,
}),
- payment_method.payment_method_type,
- Some(mandate_connector_details),
- ))
+ payment_method_type: payment_method.payment_method_type,
+ mandate_connector: Some(mandate_connector_details),
+ mandate_data: None,
+ payment_method_info: None,
+ })
}
}
@@ -792,7 +852,7 @@ pub fn validate_mandate(
let req: api::MandateValidationFields = req.into();
match req.validate_and_get_mandate_type().change_context(
errors::ApiErrorResponse::MandateValidationFailed {
- reason: "Expected one out of mandate_id and mandate_data but got both".into(),
+ reason: "Expected one out of recurring_details and mandate_data but got both".into(),
},
)? {
Some(api::MandateTransactionType::NewMandateTransaction) => {
@@ -809,6 +869,23 @@ pub fn validate_mandate(
}
}
+pub fn validate_recurring_details_and_token(
+ recurring_details: &Option<RecurringDetails>,
+ payment_token: &Option<String>,
+) -> CustomResult<(), errors::ApiErrorResponse> {
+ utils::when(
+ recurring_details.is_some() && payment_token.is_some(),
+ || {
+ Err(report!(errors::ApiErrorResponse::PreconditionFailed {
+ message: "Expected one out of recurring_details and payment_token but got both"
+ .into()
+ }))
+ },
+ )?;
+
+ Ok(())
+}
+
fn validate_new_mandate_request(
req: api::MandateValidationFields,
is_confirm_operation: bool,
@@ -940,7 +1017,8 @@ pub fn create_complete_authorize_url(
}
fn validate_recurring_mandate(req: api::MandateValidationFields) -> RouterResult<()> {
- req.mandate_id.check_value_present("mandate_id")?;
+ req.recurring_details
+ .check_value_present("recurring_details")?;
req.customer_id.check_value_present("customer_id")?;
@@ -1950,7 +2028,8 @@ pub(crate) fn validate_payment_method_fields_present(
utils::when(
req.payment_method.is_some()
&& req.payment_method_data.is_none()
- && req.payment_token.is_none(),
+ && req.payment_token.is_none()
+ && req.recurring_details.is_none(),
|| {
Err(errors::ApiErrorResponse::MissingRequiredField {
field_name: "payment_method_data",
diff --git a/crates/router/src/core/payments/operations/payment_approve.rs b/crates/router/src/core/payments/operations/payment_approve.rs
index 65b856364cc..a2132bed8c1 100644
--- a/crates/router/src/core/payments/operations/payment_approve.rs
+++ b/crates/router/src/core/payments/operations/payment_approve.rs
@@ -178,6 +178,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
authorizations: vec![],
frm_metadata: None,
authentication: None,
+ recurring_details: None,
};
let get_trackers_response = operations::GetTrackerResponse {
diff --git a/crates/router/src/core/payments/operations/payment_cancel.rs b/crates/router/src/core/payments/operations/payment_cancel.rs
index b25c0e2b909..ab5feb5d9b5 100644
--- a/crates/router/src/core/payments/operations/payment_cancel.rs
+++ b/crates/router/src/core/payments/operations/payment_cancel.rs
@@ -187,6 +187,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
authorizations: vec![],
frm_metadata: None,
authentication: None,
+ recurring_details: None,
};
let get_trackers_response = operations::GetTrackerResponse {
diff --git a/crates/router/src/core/payments/operations/payment_capture.rs b/crates/router/src/core/payments/operations/payment_capture.rs
index 47d339f15be..4445589f42f 100644
--- a/crates/router/src/core/payments/operations/payment_capture.rs
+++ b/crates/router/src/core/payments/operations/payment_capture.rs
@@ -231,6 +231,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
authorizations: vec![],
frm_metadata: None,
authentication: None,
+ recurring_details: None,
};
let get_trackers_response = operations::GetTrackerResponse {
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 8a773904ea3..b788ebc95f7 100644
--- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs
+++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs
@@ -10,6 +10,7 @@ use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, Valida
use crate::{
core::{
errors::{self, CustomResult, RouterResult, StorageErrorExt},
+ mandate::helpers::MandateGenericData,
payment_methods::PaymentMethodRetrieve,
payments::{self, helpers, operations, CustomerDetails, PaymentAddress, PaymentData},
utils as core_utils,
@@ -71,17 +72,18 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
"confirm",
)?;
- let (
+ let MandateGenericData {
token,
payment_method,
payment_method_type,
- setup_mandate,
+ mandate_data,
recurring_mandate_payment_data,
mandate_connector,
- ) = helpers::get_token_pm_type_mandate_details(
+ payment_method_info,
+ } = helpers::get_token_pm_type_mandate_details(
state,
request,
- mandate_type.clone(),
+ mandate_type.to_owned(),
merchant_account,
key_store,
)
@@ -225,7 +227,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
payment_intent.metadata = request.metadata.clone().or(payment_intent.metadata);
// The operation merges mandate data from both request and payment_attempt
- let setup_mandate = setup_mandate.map(Into::into);
+ let setup_mandate = mandate_data.map(Into::into);
let mandate_details_present =
payment_attempt.mandate_details.is_some() || request.mandate_data.is_some();
@@ -270,7 +272,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
.payment_method_data
.as_ref()
.map(|pmd| pmd.payment_method_data.clone()),
- payment_method_info: None,
+ payment_method_info,
force_sync: None,
refunds: vec![],
disputes: vec![],
@@ -291,6 +293,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
authorizations: vec![],
authentication: None,
frm_metadata: None,
+ recurring_details: request.recurring_details.clone(),
};
let customer_details = Some(CustomerDetails {
@@ -455,6 +458,11 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::Paymen
let mandate_type =
helpers::validate_mandate(request, payments::is_operation_confirm(self))?;
+ helpers::validate_recurring_details_and_token(
+ &request.recurring_details,
+ &request.payment_token,
+ )?;
+
Ok((
Box::new(self),
operations::ValidateResult {
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index cb4226bcfbe..a0caf5e1c94 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -15,6 +15,7 @@ use crate::{
authentication,
blocklist::utils as blocklist_utils,
errors::{self, CustomResult, RouterResult, StorageErrorExt},
+ mandate::helpers::MandateGenericData,
payment_methods::PaymentMethodRetrieve,
payments::{
self, helpers, operations, populate_surcharge_details, CustomerDetails, PaymentAddress,
@@ -351,14 +352,15 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
.setup_future_usage
.or(payment_intent.setup_future_usage);
- let (
+ let MandateGenericData {
token,
payment_method,
payment_method_type,
- mut setup_mandate,
+ mandate_data,
recurring_mandate_payment_data,
mandate_connector,
- ) = mandate_details;
+ payment_method_info,
+ } = mandate_details;
let browser_info = request
.browser_info
@@ -406,7 +408,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
(Some(token_data), payment_method_info)
} else {
- (None, None)
+ (None, payment_method_info)
};
payment_attempt.payment_method = payment_method.or(payment_attempt.payment_method);
@@ -478,7 +480,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
.or(payment_attempt.business_sub_label);
// The operation merges mandate data from both request and payment_attempt
- setup_mandate = setup_mandate.map(|mut sm| {
+ let setup_mandate = mandate_data.map(|mut sm| {
sm.mandate_type = payment_attempt.mandate_details.clone().or(sm.mandate_type);
sm.update_mandate_id = payment_attempt
.mandate_data
@@ -619,6 +621,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
authorizations: vec![],
frm_metadata: request.frm_metadata.clone(),
authentication,
+ recurring_details: request.recurring_details.clone(),
};
let get_trackers_response = operations::GetTrackerResponse {
@@ -1199,6 +1202,11 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::Paymen
let mandate_type =
helpers::validate_mandate(request, payments::is_operation_confirm(self))?;
+ helpers::validate_recurring_details_and_token(
+ &request.recurring_details,
+ &request.payment_token,
+ )?;
+
let payment_id = request
.payment_id
.clone()
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index 58675bf62cd..6dce6db9d9b 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -1,6 +1,6 @@
use std::marker::PhantomData;
-use api_models::enums::FrmSuggestion;
+use api_models::{enums::FrmSuggestion, mandates::RecurringDetails};
use async_trait::async_trait;
use common_utils::ext_traits::{AsyncExt, Encode, ValueExt};
use data_models::{
@@ -19,6 +19,7 @@ use crate::{
consts,
core::{
errors::{self, CustomResult, RouterResult, StorageErrorExt},
+ mandate::helpers::MandateGenericData,
payment_link,
payment_methods::PaymentMethodRetrieve,
payments::{self, helpers, operations, CustomerDetails, PaymentAddress, PaymentData},
@@ -104,14 +105,15 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
})?
};
- let (
+ let MandateGenericData {
token,
payment_method,
payment_method_type,
- setup_mandate,
+ mandate_data,
recurring_mandate_payment_data,
mandate_connector,
- ) = helpers::get_token_pm_type_mandate_details(
+ payment_method_info,
+ } = helpers::get_token_pm_type_mandate_details(
state,
request,
mandate_type,
@@ -291,6 +293,14 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
let mandate_id = request
.mandate_id
.as_ref()
+ .or_else(|| {
+ request.recurring_details
+ .as_ref()
+ .and_then(|recurring_details| match recurring_details {
+ RecurringDetails::MandateId(id) => Some(id),
+ _ => None,
+ })
+ })
.async_and_then(|mandate_id| async {
let mandate = db
.find_mandate_by_merchant_id_mandate_id(merchant_id, mandate_id)
@@ -359,7 +369,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
.transpose()?;
// The operation merges mandate data from both request and payment_attempt
- let setup_mandate = setup_mandate.map(MandateData::from);
+ let setup_mandate = mandate_data.map(MandateData::from);
let customer_acceptance = request.customer_acceptance.clone().map(From::from);
@@ -398,7 +408,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
token_data: None,
confirm: request.confirm,
payment_method_data: payment_method_data_after_card_bin_call,
- payment_method_info: None,
+ payment_method_info,
refunds: vec![],
disputes: vec![],
attempts: None,
@@ -419,6 +429,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
authorizations: vec![],
authentication: None,
frm_metadata: request.frm_metadata.clone(),
+ recurring_details: request.recurring_details.clone(),
};
let get_trackers_response = operations::GetTrackerResponse {
@@ -676,6 +687,11 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::Paymen
let mandate_type =
helpers::validate_mandate(request, payments::is_operation_confirm(self))?;
+ helpers::validate_recurring_details_and_token(
+ &request.recurring_details,
+ &request.payment_token,
+ )?;
+
if request.confirm.unwrap_or(false) {
helpers::validate_pm_or_token_given(
&request.payment_method,
diff --git a/crates/router/src/core/payments/operations/payment_reject.rs b/crates/router/src/core/payments/operations/payment_reject.rs
index 591ecb0a118..e1d58b032aa 100644
--- a/crates/router/src/core/payments/operations/payment_reject.rs
+++ b/crates/router/src/core/payments/operations/payment_reject.rs
@@ -174,6 +174,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
authorizations: vec![],
authentication: None,
frm_metadata: None,
+ recurring_details: None,
};
let get_trackers_response = operations::GetTrackerResponse {
diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs
index 805b5fb3630..25b419e3222 100644
--- a/crates/router/src/core/payments/operations/payment_session.rs
+++ b/crates/router/src/core/payments/operations/payment_session.rs
@@ -199,6 +199,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
authorizations: vec![],
authentication: None,
frm_metadata: None,
+ recurring_details: None,
};
let get_trackers_response = operations::GetTrackerResponse {
diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rs
index 520336be0e1..465a2e5818d 100644
--- a/crates/router/src/core/payments/operations/payment_start.rs
+++ b/crates/router/src/core/payments/operations/payment_start.rs
@@ -186,6 +186,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
authorizations: vec![],
authentication: None,
frm_metadata: None,
+ recurring_details: None,
};
let get_trackers_response = operations::GetTrackerResponse {
diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs
index 101d997db21..4d616146908 100644
--- a/crates/router/src/core/payments/operations/payment_status.rs
+++ b/crates/router/src/core/payments/operations/payment_status.rs
@@ -462,6 +462,7 @@ async fn get_tracker_for_sync<
authorizations,
authentication,
frm_metadata: None,
+ recurring_details: None,
};
let get_trackers_response = operations::GetTrackerResponse {
diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs
index 2a0b99bc54b..684f7c4b698 100644
--- a/crates/router/src/core/payments/operations/payment_update.rs
+++ b/crates/router/src/core/payments/operations/payment_update.rs
@@ -1,6 +1,8 @@
use std::marker::PhantomData;
-use api_models::{enums::FrmSuggestion, payments::RequestSurchargeDetails};
+use api_models::{
+ enums::FrmSuggestion, mandates::RecurringDetails, payments::RequestSurchargeDetails,
+};
use async_trait::async_trait;
use common_utils::ext_traits::{AsyncExt, Encode, ValueExt};
use error_stack::{report, IntoReport, ResultExt};
@@ -11,6 +13,7 @@ use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, Valida
use crate::{
core::{
errors::{self, CustomResult, RouterResult, StorageErrorExt},
+ mandate::helpers::MandateGenericData,
payment_methods::PaymentMethodRetrieve,
payments::{self, helpers, operations, CustomerDetails, PaymentAddress, PaymentData},
utils as core_utils,
@@ -94,17 +97,19 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
)?;
helpers::authenticate_client_secret(request.client_secret.as_ref(), &payment_intent)?;
- let (
+
+ let MandateGenericData {
token,
payment_method,
payment_method_type,
- setup_mandate,
+ mandate_data,
recurring_mandate_payment_data,
mandate_connector,
- ) = helpers::get_token_pm_type_mandate_details(
+ payment_method_info,
+ } = helpers::get_token_pm_type_mandate_details(
state,
request,
- mandate_type.clone(),
+ mandate_type.to_owned(),
merchant_account,
key_store,
)
@@ -263,6 +268,14 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
let mandate_id = request
.mandate_id
.as_ref()
+ .or_else(|| {
+ request.recurring_details
+ .as_ref()
+ .and_then(|recurring_details| match recurring_details {
+ RecurringDetails::MandateId(id) => Some(id),
+ _ => None,
+ })
+ })
.async_and_then(|mandate_id| async {
let mandate = db
.find_mandate_by_merchant_id_mandate_id(merchant_id, mandate_id)
@@ -357,7 +370,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
.transpose()?;
// The operation merges mandate data from both request and payment_attempt
- let setup_mandate = setup_mandate.map(Into::into);
+ let setup_mandate = mandate_data.map(Into::into);
let mandate_details_present =
payment_attempt.mandate_details.is_some() || request.mandate_data.is_some();
helpers::validate_mandate_data_and_future_usage(
@@ -405,7 +418,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
.payment_method_data
.as_ref()
.map(|pmd| pmd.payment_method_data.clone()),
- payment_method_info: None,
+ payment_method_info,
force_sync: None,
refunds: vec![],
disputes: vec![],
@@ -426,6 +439,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
authorizations: vec![],
authentication: None,
frm_metadata: request.frm_metadata.clone(),
+ recurring_details: request.recurring_details.clone(),
};
let get_trackers_response = operations::GetTrackerResponse {
@@ -737,6 +751,11 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::Paymen
let mandate_type = helpers::validate_mandate(request, false)?;
+ helpers::validate_recurring_details_and_token(
+ &request.recurring_details,
+ &request.payment_token,
+ )?;
+
Ok((
Box::new(self),
operations::ValidateResult {
diff --git a/crates/router/src/core/payments/operations/payments_incremental_authorization.rs b/crates/router/src/core/payments/operations/payments_incremental_authorization.rs
index ab7ab56d94f..f28b1d55c32 100644
--- a/crates/router/src/core/payments/operations/payments_incremental_authorization.rs
+++ b/crates/router/src/core/payments/operations/payments_incremental_authorization.rs
@@ -152,6 +152,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
authorizations: vec![],
authentication: None,
frm_metadata: None,
+ recurring_details: None,
};
let get_trackers_response = operations::GetTrackerResponse {
diff --git a/crates/router/src/types/api/payments.rs b/crates/router/src/types/api/payments.rs
index 8e13f6c9935..d465300dd61 100644
--- a/crates/router/src/types/api/payments.rs
+++ b/crates/router/src/types/api/payments.rs
@@ -115,10 +115,11 @@ impl MandateValidationFieldsExt for MandateValidationFields {
fn validate_and_get_mandate_type(
&self,
) -> errors::CustomResult<Option<MandateTransactionType>, errors::ValidationError> {
- match (&self.mandate_data, &self.mandate_id) {
+ match (&self.mandate_data, &self.recurring_details) {
(None, None) => Ok(None),
(Some(_), Some(_)) => Err(errors::ValidationError::InvalidValue {
- message: "Expected one out of mandate_id and mandate_data but got both".to_string(),
+ message: "Expected one out of recurring_details and mandate_data but got both"
+ .to_string(),
})
.into_report(),
(_, Some(_)) => Ok(Some(MandateTransactionType::RecurringMandateTransaction)),
diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json
index 2005f9c11e0..fa9c7435632 100644
--- a/openapi/openapi_spec.json
+++ b/openapi/openapi_spec.json
@@ -13334,6 +13334,14 @@
"description": "Whether to perform external authentication (if applicable)",
"example": true,
"nullable": true
+ },
+ "recurring_details": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/RecurringDetails"
+ }
+ ],
+ "nullable": true
}
}
},
@@ -13726,6 +13734,14 @@
"description": "Whether to perform external authentication (if applicable)",
"example": true,
"nullable": true
+ },
+ "recurring_details": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/RecurringDetails"
+ }
+ ],
+ "nullable": true
}
}
},
@@ -14220,6 +14236,14 @@
"description": "Whether to perform external authentication (if applicable)",
"example": true,
"nullable": true
+ },
+ "recurring_details": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/RecurringDetails"
+ }
+ ],
+ "nullable": true
}
}
},
@@ -15220,6 +15244,14 @@
"description": "Whether to perform external authentication (if applicable)",
"example": true,
"nullable": true
+ },
+ "recurring_details": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/RecurringDetails"
+ }
+ ],
+ "nullable": true
}
}
},
@@ -16129,6 +16161,49 @@
"disabled"
]
},
+ "RecurringDetails": {
+ "oneOf": [
+ {
+ "type": "object",
+ "required": [
+ "type",
+ "data"
+ ],
+ "properties": {
+ "type": {
+ "type": "string",
+ "enum": [
+ "mandate_id"
+ ]
+ },
+ "data": {
+ "type": "string"
+ }
+ }
+ },
+ {
+ "type": "object",
+ "required": [
+ "type",
+ "data"
+ ],
+ "properties": {
+ "type": {
+ "type": "string",
+ "enum": [
+ "payment_method_id"
+ ]
+ },
+ "data": {
+ "type": "string"
+ }
+ }
+ }
+ ],
+ "discriminator": {
+ "propertyName": "type"
+ }
+ },
"RedirectResponse": {
"type": "object",
"properties": {
|
2024-03-19T12:12: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 -->
When a mandate is created on connector's end, we store the connector mandate details in our payment methods table. Now in order to make recurring payment with this, we basically have to do a token based payment where set the `setup_future_usage = off_session` and we list the payment methods of a customer and make a payment with payment token. But we should also allow off-session payments using payment method id without having to list customer payment methods. For this, we accept `off_session = true` and payment method id in the request and make a recurring mandate payment.
### 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`
-->
Api contract changes -
Added new field in `PaymentsRequest`:
```
"recurring_details": {
"type": "payment_method_id/mandate_id",
"data": "String"
},
```
## 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. mca creation -
```
curl --location 'http://localhost:8080/account/merchant_1710841026/connectors' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: test_admin' \
--data '{
"connector_type": "fiz_operations",
"business_country": "US",
"business_label": "default",
"connector_name": "cybersource",
"connector_account_details": {
"auth_type": "SignatureKey",
"api_key": "abc",
"api_secret": "xyz",
"key1": "key"
},
"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": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]
}
],
"connector_webhook_details": {
"merchant_secret": "Xavior"
}
}'
```
2. Setup mandate on connector's end
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: abc' \
--data-raw '{
"amount": 0,
"currency": "USD",
"confirm": true,
"profile_id": "pro_ByhEgJFlWSahAgSqaUZl",
"capture_method": "automatic",
"customer_id": "mandate_customer1",
"email": "guest@example.com",
"setup_future_usage": "off_session",
"customer_acceptance": {
"acceptance_type": "online"
},
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": "Test Holder",
"card_cvc": "737"
}
},
"payment_type": "setup_mandate",
"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"
}'
```
db entry -

3. Recurring payment using `payment_method_id`
```
curl --location 'http://localhost:8080/payments' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header 'api-key: abc' \
--data-raw '{
"amount": 499,
"currency": "USD",
"confirm": true,
"profile_id": "pro_ByhEgJFlWSahAgSqaUZl",
"capture_method": "automatic",
"customer_id": "mandate_customer1",
"email": "guest@example.com",
"off_session": true,
"recurring_details": {
"type": "payment_method_id",
"data": "pm_lmTnIO5EdCiiMgRPrV9x"
},
"payment_method": "card",
"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"
}'
```
Payment succeded -

Also try creating mandate on hyperswitch end by providing mandate_data in setup mandate request and get the `mandate_id`. Do the recurring payment with `mandate_id`. Also try another recurring payment with below structure
```
"recurring_details": {
"type": "mandate_id",
"data": "xyz"
}
```
## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
0f8384dde996a455920bd4127c1d0ce62d5312ba
|
|
juspay/hyperswitch
|
juspay__hyperswitch-3783
|
Bug: [FEATURE] [BOA/Cybersource] Pass commerce indicator using card network for apple pay
### Feature Description
Apple pay transactions via BOA and Cybersource require a specific field `commerce_indicator` which is based on the card network type used during apple pay transactions.
https://docs.cybersource.com/content/dam/documentation/en/apple-pay/fdiglobal/so/applepay-so-fdiglobal.pdf
### Possible Implementation
`commerce_indicator` should be passed using the card network data being shared from SDK during apple pay payments for BOA and Cybersource
### 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/bankofamerica/transformers.rs b/crates/router/src/connector/bankofamerica/transformers.rs
index 235321f1ac6..0be25b078bc 100644
--- a/crates/router/src/connector/bankofamerica/transformers.rs
+++ b/crates/router/src/connector/bankofamerica/transformers.rs
@@ -330,21 +330,34 @@ impl
From<(
&BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>,
Option<PaymentSolution>,
+ Option<String>,
)> for ProcessingInformation
{
fn from(
- (item, solution): (
+ (item, solution, network): (
&BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>,
Option<PaymentSolution>,
+ Option<String>,
),
) -> Self {
+ let commerce_indicator = match network {
+ Some(card_network) => match card_network.to_lowercase().as_str() {
+ "amex" => "aesk",
+ "discover" => "dipb",
+ "mastercard" => "spa",
+ "visa" => "internet",
+ _ => "internet",
+ },
+ None => "internet",
+ }
+ .to_string();
Self {
capture: Some(matches!(
item.router_data.request.capture_method,
Some(enums::CaptureMethod::Automatic) | None
)),
payment_solution: solution.map(String::from),
- commerce_indicator: String::from("internet"),
+ commerce_indicator,
}
}
}
@@ -552,7 +565,7 @@ impl
card_type,
},
});
- let processing_information = ProcessingInformation::from((item, None));
+ let processing_information = ProcessingInformation::from((item, None, None));
let client_reference_information = ClientReferenceInformation::from(item);
let merchant_defined_information =
item.router_data.request.metadata.clone().map(|metadata| {
@@ -574,20 +587,25 @@ impl
TryFrom<(
&BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>,
Box<ApplePayPredecryptData>,
+ payments::ApplePayWalletData,
)> for BankOfAmericaPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- (item, apple_pay_data): (
+ (item, apple_pay_data, apple_pay_wallet_data): (
&BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>,
Box<ApplePayPredecryptData>,
+ payments::ApplePayWalletData,
),
) -> Result<Self, Self::Error> {
let email = item.router_data.request.get_email()?;
let bill_to = build_bill_to(item.router_data.get_billing()?, email)?;
let order_information = OrderInformationWithBill::from((item, bill_to));
- let processing_information =
- ProcessingInformation::from((item, Some(PaymentSolution::ApplePay)));
+ let processing_information = ProcessingInformation::from((
+ item,
+ Some(PaymentSolution::ApplePay),
+ Some(apple_pay_wallet_data.payment_method.network),
+ ));
let client_reference_information = ClientReferenceInformation::from(item);
let expiration_month = apple_pay_data.get_expiry_month()?;
let expiration_year = apple_pay_data.get_four_digit_expiry_year()?;
@@ -640,7 +658,7 @@ impl
},
});
let processing_information =
- ProcessingInformation::from((item, Some(PaymentSolution::GooglePay)));
+ ProcessingInformation::from((item, Some(PaymentSolution::GooglePay), None));
let client_reference_information = ClientReferenceInformation::from(item);
let merchant_defined_information =
item.router_data.request.metadata.clone().map(|metadata| {
@@ -672,7 +690,7 @@ impl TryFrom<&BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>>
match item.router_data.payment_method_token.clone() {
Some(payment_method_token) => match payment_method_token {
types::PaymentMethodToken::ApplePayDecrypt(decrypt_data) => {
- Self::try_from((item, decrypt_data))
+ Self::try_from((item, decrypt_data, apple_pay_data))
}
types::PaymentMethodToken::Token(_) => {
Err(errors::ConnectorError::InvalidWalletToken)?
@@ -685,6 +703,7 @@ impl TryFrom<&BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>>
let processing_information = ProcessingInformation::from((
item,
Some(PaymentSolution::ApplePay),
+ Some(apple_pay_data.payment_method.network),
));
let client_reference_information =
ClientReferenceInformation::from(item);
diff --git a/crates/router/src/connector/checkout/transformers.rs b/crates/router/src/connector/checkout/transformers.rs
index f96bd50ffc8..2a20999085d 100644
--- a/crates/router/src/connector/checkout/transformers.rs
+++ b/crates/router/src/connector/checkout/transformers.rs
@@ -207,7 +207,7 @@ pub struct ApplePayPredecrypt {
token_type: String,
expiry_month: Secret<String>,
expiry_year: Secret<String>,
- eci: Option<Secret<String>>,
+ eci: Option<String>,
cryptogram: Secret<String>,
}
diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs
index 646fe179da6..4bb28439b7f 100644
--- a/crates/router/src/connector/cybersource/transformers.rs
+++ b/crates/router/src/connector/cybersource/transformers.rs
@@ -489,13 +489,15 @@ impl
TryFrom<(
&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>,
Option<PaymentSolution>,
+ Option<String>,
)> for ProcessingInformation
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- (item, solution): (
+ (item, solution, network): (
&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>,
Option<PaymentSolution>,
+ Option<String>,
),
) -> Result<Self, Self::Error> {
let (action_list, action_token_types, authorization_options) =
@@ -539,6 +541,17 @@ impl
} else {
(None, None, None)
};
+ let commerce_indicator = match network {
+ Some(card_network) => match card_network.to_lowercase().as_str() {
+ "amex" => "aesk",
+ "discover" => "dipb",
+ "mastercard" => "spa",
+ "visa" => "internet",
+ _ => "internet",
+ },
+ None => "internet",
+ }
+ .to_string();
Ok(Self {
capture: Some(matches!(
item.router_data.request.capture_method,
@@ -549,7 +562,7 @@ impl
action_token_types,
authorization_options,
capture_options: None,
- commerce_indicator: String::from("internet"),
+ commerce_indicator,
})
}
}
@@ -721,7 +734,7 @@ impl
},
});
- let processing_information = ProcessingInformation::try_from((item, None))?;
+ let processing_information = ProcessingInformation::try_from((item, None, None))?;
let client_reference_information = ClientReferenceInformation::from(item);
let merchant_defined_information =
item.router_data.request.metadata.clone().map(|metadata| {
@@ -820,20 +833,25 @@ impl
TryFrom<(
&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>,
Box<ApplePayPredecryptData>,
+ payments::ApplePayWalletData,
)> for CybersourcePaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- (item, apple_pay_data): (
+ (item, apple_pay_data, apple_pay_wallet_data): (
&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>,
Box<ApplePayPredecryptData>,
+ payments::ApplePayWalletData,
),
) -> Result<Self, Self::Error> {
let email = item.router_data.request.get_email()?;
let bill_to = build_bill_to(item.router_data.get_billing()?, email)?;
let order_information = OrderInformationWithBill::from((item, bill_to));
- let processing_information =
- ProcessingInformation::try_from((item, Some(PaymentSolution::ApplePay)))?;
+ let processing_information = ProcessingInformation::try_from((
+ item,
+ Some(PaymentSolution::ApplePay),
+ Some(apple_pay_wallet_data.payment_method.network),
+ ))?;
let client_reference_information = ClientReferenceInformation::from(item);
let expiration_month = apple_pay_data.get_expiry_month()?;
let expiration_year = apple_pay_data.get_four_digit_expiry_year()?;
@@ -887,7 +905,7 @@ impl
},
});
let processing_information =
- ProcessingInformation::try_from((item, Some(PaymentSolution::GooglePay)))?;
+ ProcessingInformation::try_from((item, Some(PaymentSolution::GooglePay), None))?;
let client_reference_information = ClientReferenceInformation::from(item);
let merchant_defined_information =
item.router_data.request.metadata.clone().map(|metadata| {
@@ -922,7 +940,7 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>>
match item.router_data.payment_method_token.clone() {
Some(payment_method_token) => match payment_method_token {
types::PaymentMethodToken::ApplePayDecrypt(decrypt_data) => {
- Self::try_from((item, decrypt_data))
+ Self::try_from((item, decrypt_data, apple_pay_data))
}
types::PaymentMethodToken::Token(_) => {
Err(errors::ConnectorError::InvalidWalletToken)?
@@ -934,9 +952,12 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>>
build_bill_to(item.router_data.get_billing()?, email)?;
let order_information =
OrderInformationWithBill::from((item, bill_to));
- let processing_information = ProcessingInformation::try_from(
- (item, Some(PaymentSolution::ApplePay)),
- )?;
+ let processing_information =
+ ProcessingInformation::try_from((
+ item,
+ Some(PaymentSolution::ApplePay),
+ Some(apple_pay_data.payment_method.network),
+ ))?;
let client_reference_information =
ClientReferenceInformation::from(item);
let payment_information = PaymentInformation::ApplePayToken(
@@ -1048,7 +1069,7 @@ impl
String,
),
) -> Result<Self, Self::Error> {
- let processing_information = ProcessingInformation::try_from((item, None))?;
+ let processing_information = ProcessingInformation::try_from((item, None, None))?;
let payment_instrument = CybersoucrePaymentInstrument {
id: connector_mandate_id,
};
diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs
index 8c370317c62..7c7a534f1c0 100644
--- a/crates/router/src/connector/stripe/transformers.rs
+++ b/crates/router/src/connector/stripe/transformers.rs
@@ -489,7 +489,7 @@ pub struct StripeApplePayPredecrypt {
#[serde(rename = "card[cryptogram]")]
cryptogram: Secret<String>,
#[serde(rename = "card[eci]")]
- eci: Option<Secret<String>>,
+ eci: Option<String>,
#[serde(rename = "card[tokenization_method]")]
tokenization_method: String,
}
diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs
index 7951246790f..fde9195143e 100644
--- a/crates/router/src/connector/utils.rs
+++ b/crates/router/src/connector/utils.rs
@@ -949,7 +949,6 @@ impl ApplePayDecrypt for Box<ApplePayPredecryptData> {
Ok(Secret::new(format!(
"20{}",
self.application_expiration_date
- .peek()
.get(0..2)
.ok_or(errors::ConnectorError::RequestEncodingFailed)?
)))
@@ -958,7 +957,6 @@ impl ApplePayDecrypt for Box<ApplePayPredecryptData> {
fn get_expiry_month(&self) -> Result<Secret<String>, Error> {
Ok(Secret::new(
self.application_expiration_date
- .peek()
.get(2..4)
.ok_or(errors::ConnectorError::RequestEncodingFailed)?
.to_owned(),
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 050b0dd4b7b..e13d54f80d1 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -1129,6 +1129,8 @@ where
.parse_value::<router_types::ApplePayPredecryptData>("ApplePayPredecryptData")
.change_context(errors::ApiErrorResponse::InternalServerError)?;
+ logger::debug!(?apple_pay_predecrypt);
+
router_data.payment_method_token = Some(router_types::PaymentMethodToken::ApplePayDecrypt(
Box::new(apple_pay_predecrypt),
));
diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs
index e163de9a5da..07691879d4a 100644
--- a/crates/router/src/types.rs
+++ b/crates/router/src/types.rs
@@ -334,9 +334,9 @@ pub enum PaymentMethodToken {
#[serde(rename_all = "camelCase")]
pub struct ApplePayPredecryptData {
pub application_primary_account_number: Secret<String>,
- pub application_expiration_date: Secret<String>,
- pub currency_code: Secret<String>,
- pub transaction_amount: Secret<i64>,
+ pub application_expiration_date: String,
+ pub currency_code: String,
+ pub transaction_amount: i64,
pub device_manufacturer_identifier: Secret<String>,
pub payment_data_type: Secret<String>,
pub payment_data: ApplePayCryptogramData,
@@ -346,7 +346,7 @@ pub struct ApplePayPredecryptData {
#[serde(rename_all = "camelCase")]
pub struct ApplePayCryptogramData {
pub online_payment_cryptogram: Secret<String>,
- pub eci_indicator: Option<Secret<String>>,
+ pub eci_indicator: Option<String>,
}
#[derive(Debug, Clone)]
|
2024-02-23T08:05: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 -->
Apple pay transactions via BOA and Cybersource require a specific field `commerce_indicator` which is based on the card network type used during apple pay transactions.
https://docs.cybersource.com/content/dam/documentation/en/apple-pay/fdiglobal/so/applepay-so-fdiglobal.pdf
This data is now being passed using the card network data being shared from SDK during apple pay 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).
-->
https://github.com/juspay/hyperswitch/issues/3783
## 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 payments need to be tested using simplified and manual flow for connectors BOA and Cybersource.

## 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
- [ ] I added a [CHANGELOG](/CHANGELOG.md) entry if applicable
|
21d2b6ee2cacecc6da3a3c8ef07dedfb417752b0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.